#include
#include
#include
struct msg
{
struct msg *next;
int num;
};
struct msg *head;
pthread_cond_t has_product=PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
void *producer(void *p)
{
struct msg *mp;
int i;
for(i=0;i<20;i++)
{
mp=malloc(sizeof(struct msg));
mp->num=rand()%1000+1;
printf("Producer %d\n",mp->num);
pthread_mutex_lock(&lock);
mp->next=head;
head=mp;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&has_product); //先解锁再唤醒线程,可避免唤醒线程无法lock造成的阻塞
sleep(rand()%5);
}
}
void *consumer(void *p)
{
struct msg *mp;
int i;
for(i=0;i<20;i++)
{
pthread_mutex_lock(&lock); //互斥量用以保护临界资源即条件变量has_product
while(head==NULL)
pthread_cond_wait(&has_product,&lock); //阻塞线程,释放mutex
mp=head;
head=mp->next;
pthread_mutex_unlock(&lock);
printf("Consumer %d\n",mp->num);
free(mp);
sleep(rand()%5);
}
}
int main()
{
pthread_t pt,ct;
srand(time(NULL));
pthread_create(&pt,NULL,producer,NULL);
pthread_create(&ct,NULL,consumer,NULL);
pthread_join(pt,NULL);
pthread_join(ct,NULL);
return 0;
}
注:之所以要引入条件变量是需要进行条件判断所致,而用互斥锁来保护条件满足信号是由于条件满足信号本身就是临界资源。旨在防止在判断条件与等待操作之间隙条件满足信号被其他线程改变而未能正确判断因而可能导致的无限等待,即此例中
while(head==NULL)与
pthread_cond_wait(&has_product,&lock);
pthread_cond_wait(&has_product,&lock);
执行之间隙head的改变未能正确捕捉