今天我学习了pthread,我写了一个关于制作人和消费者问题的玩具示例。但是当我把 pthread_cond_signal放在循环中而不是循环时,我发现程序的动作是不同的.Here是原始代码。
#include <pthread.h>
#include <stdio.h>
int good_count = 0;
int total = 0;
pthread_mutex_t mt;
pthread_cond_t cv;
volatile int producer_wait = 1;
void* produce()
{
pthread_mutex_lock(&mt);
printf("Producer Wait;\n");
producer_wait = 1;
pthread_cond_wait(&cv, &mt);
producer_wait = 0;
printf("Received a signal\n");
pthread_mutex_unlock(&mt);
pthread_exit(NULL);
}
void* consume()
{
pthread_mutex_lock(&mt);
while(producer_wait)
{
pthread_cond_signal(&cv);
sleep(1);
}
//pthread_cond_signal(&cv);
pthread_mutex_unlock(&mt);
pthread_exit(NULL);
}
int main()
{
pthread_t threads[2];
pthread_attr_t attr;
/*initialize mutex and cond */
pthread_mutex_init(&mt, NULL);
pthread_cond_init(&cv, NULL);
/*initialize thread attribute*/
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, produce, NULL);
pthread_create(&threads[1], &attr, consume, NULL);
int i;
for (i = 0; i < 2; i++) {
pthread_join(threads[i], NULL);
}
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&mt);
pthread_cond_destroy(&cv);
pthread_exit(NULL);
}
pthread_cond_wait(&amp; cv,&amp; mt)中的生产者线程块,while循环中的消费者线程调用pthread_cond_signal(&amp; cv)不生效。但是如果我修改了这样的consume()函数代码,然后它就会生效。
void* consume()
{
pthread_mutex_lock(&mt);
/*while(producer_wait)
{
pthread_cond_signal(&cv);
sleep(1);
}*/
pthread_cond_signal(&cv);
pthread_mutex_unlock(&mt);
pthread_exit(NULL);
}
我很困惑,希望得到答案!
我修改消耗函数,将pthread_mutex_lock(&amp; mt)和pthread_mutex_unlock(&amp; mt)移入while循环,并注释sleep(1),消费者可以释放互斥锁。这样,生产者线程就可以接收信号。但如果我取消注释sleep(1),则生产者线程无法接收信号。为什么?
void* consume()
{
while(producer_wait)
{
pthread_mutex_lock(&mt);
pthread_cond_signal(&cv);
//sleep(1);
pthread_mutex_unlock(&mt);
}
pthread_exit(NULL);
}
消费者线程
答案 0 :(得分:1)
with loop,你的消费者永远不会释放互斥锁,生产者需要互斥锁继续,所以死锁