Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当pthread_cond_信号在循环中或不在循环中时,为什么操作不同_C_Linux - Fatal编程技术网

当pthread_cond_信号在循环中或不在循环中时,为什么操作不同

当pthread_cond_信号在循环中或不在循环中时,为什么操作不同,c,linux,C,Linux,今天我学习了pthread,我写了一个关于生产者和消费者问题的玩具示例。但是我发现当我将pthread\u cond\u信号放入循环或不放入循环时,程序的动作是不同的 #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*

今天我学习了pthread,我写了一个关于生产者和消费者问题的玩具示例。但是我发现当我将pthread\u cond\u信号放入循环或不放入循环时,程序的动作是不同的

#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\u mutex\u lock(&mt)和pthread\u mutex\u unlock(&mt)移动到while循环中,并注释sleep(1),消费者可以释放互斥锁。这样,生产者线程可以接收信号。但是如果我取消注释睡眠(1)
,生产者线程就不能接收信号。为什么

void* consume()
{
    while(producer_wait)
    {
        pthread_mutex_lock(&mt);
        pthread_cond_signal(&cv);
        //sleep(1);
        pthread_mutex_unlock(&mt);
    }
    pthread_exit(NULL);
}

消费者线程

使用循环,你的消费者永远不会释放互斥锁,而生产者要求互斥锁继续,因此死锁

消费者应该等待,生产者应该发出信号。有关[pthread_cond_signal()][1]的讨论请查看。[1]:非常感谢。我在最后一个问题中附加了一个问题。消费者在持有锁时睡觉,使制作人感到痛苦。消费者在释放锁后立即获得锁,生产者没有机会运行
void* consume()
{
    while(producer_wait)
    {
        pthread_mutex_lock(&mt);
        pthread_cond_signal(&cv);
        //sleep(1);
        pthread_mutex_unlock(&mt);
    }
    pthread_exit(NULL);
}