軟件測試中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);
}