生成器使用线程和条件的消费者线程

时间:2014-04-04 15:56:36

标签: multithreading unix producer-consumer

我试图理解使用线程的生产者和消费者的代码,因为我是多线程编程的新手:

#include <sys/time.h>
#include <stdio.h>
#include <pthread.h>
#include <errno.h>
#define SIZE 10
pthread_mutex_t region_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t space_available = PTHREAD_COND_INITIALIZER;
pthread_cond_t data_available = PTHREAD_COND_INITIALIZER;
int b[SIZE]; /* buffer */
int size = 0; /* number of full elements */
int front,rear=0; /* queue */


void *producer()
{
int i = 0;
while (1) {
pthread_mutex_lock(&region_mutex);
while (size == SIZE) {

pthread_cond_broadcast(&data_available);
pthread_cond_wait(&space_available,&region_mutex);
}
if(i>99) i=-1;
add_buffer(i);
pthread_cond_broadcast(&data_available);
pthread_mutex_unlock(&region_mutex);
if (i==-1) break;
i = i + 1;
}
pthread_exit(NULL);
}


void *consumer()
{
int i,v;
While(1){
pthread_mutex_lock(&region_mutex);
while (size == 0) {
pthread_cond_broadcast(&space_available);
pthread_cond_wait(&data_available,&region_mutex);
}
v = get_buffer();
pthread_cond_broadcast(&space_available);
pthread_mutex_unlock(&region_mutex);
if (v==-1) break;
printf("got %d ",v);
}
pthread_exit(NULL);
}

这段代码的含义以及我们使用它的原因,以及99号的含义是什么:

if(i>99) i=-1;
add_buffer(i);
pthread_cond_broadcast(&data_available);
pthread_mutex_unlock(&region_mutex);
if (i==-1) break;
i = i + 1; 

提前感谢您的帮助。

0 个答案:

没有答案