软件测试中Linux系统线程编程

发表于:2010-11-02来源:作者:点击数: 标签:
软件测试中 Linux 系统线程编程 也许大家头听过,生产者-消费者 模型吧, 就是利用线程同步的方法来实现的,本博文使用线程锁的方式来实现线程同步: 头文件: ************************************************** * # include s td io.h * * # include pth

软件测试中Linux系统线程编程

也许大家头听过,生产者-消费者 模型吧, 就是利用线程同步的方法来实现的,本博文使用线程锁的方式来实现线程同步:

  头文件:

  **************************************************

  * # include <stdio.h>           *

  * # include <pthread.h>         *

  * # include <time.h>            *

  * # include <unistd.h>          *

  **************************************************

  函数声明:

  =================================================

  void reader_function(void);

  void writer_function(void);

  void consumer_item(int nu);

  int make_new_item(void);

  ===========================================

  int buffer;

  int num;

  int buffer_has_item = 0;

  pthread_mutex_t mutex;

  int main(void)

  {

  pthread_t reader;

  pthread_mutex_init(&mutex,NULL);

  pthread_create(&reader,NULL, (void *)reader_function, NULL);

  writer_function();

  return 0;

  }

  void reader_function(void)

  {

  while(1)

  {

  pthread_mutex_lock(&mutex);

  if(buffer_has_item == 1)

  {

  consumer_item(buffer);

  buffer_has_item = 0;

  }

  pthread_mutex_unlock(&mutex);

  sleep(1);

  }

  }

  void writer_function(void)

  {

  while(1)

  {

  pthread_mutex_lock(&mutex);

  if(buffer_has_item == 0)

  {

  buffer = make_new_item();

  printf(" New Item has makerd = %d\n",buffer);

  buffer_has_item = 1;

  }

  pthread_mutex_unlock(&mutex);

  sleep(1);

  }

  int make_new_item(void)

  {

  num = rand()%100;

  return num;

  }

  void consumer_item(int tmp_buffer)

  {

  int con_num;

  con_num = tmp_buffer + 1000;

  printf(" Consumer num = %d\n",con_num);

  }

原文转自:http://www.ltesting.net