为什么 pthread_cond_signal 会导致死锁

why does pthread_cond_signal cause deadlock

我是条件变量的新手,如果不使用 pthread_cond_broadcast() 就会出现死锁。

#include <iostream>
#include <pthread.h>

pthread_mutex_t m_mut = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cv = PTHREAD_COND_INITIALIZER;

bool ready = false;

void* print_id (void *ptr )
{
    pthread_mutex_lock(&m_mut);
    while (!ready) pthread_cond_wait(&cv, &m_mut);
    int id = *((int*) ptr);
    std::cout << "thread " << id  << '\n';
    pthread_mutex_unlock(&m_mut);
    pthread_exit(0);
    return NULL;
}

此处更改条件!

void go() {
    pthread_mutex_lock(&m_mut);
    ready = true;
    pthread_mutex_unlock(&m_mut);
    pthread_cond_signal(&cv);
}

go()的最后一行改成pthread_cond_broadcast(&cv);

就可以了
int main ()
{
    pthread_t threads[10];

    // spawn 10 threads:
    for (int i=0; i<10; i++)
        pthread_create(&threads[i], NULL, print_id, (void *) new int(i));

    go();

    for (int i=0; i<10; i++) pthread_join(threads[i], NULL);

    pthread_mutex_destroy(&m_mut);
    pthread_cond_destroy(&cv);

    return 0;
}

预期答案(任意顺序)是

thread 0

....

thread 9

然而,在我的机器上 (ubuntu),它什么也不打印。 谁能告诉我原因?谢谢。

来自手册页(我强调):

pthread_cond_signal restarts one of the threads that are waiting on the condition variable cond. If no threads are waiting on cond, nothing happens. If several threads are waiting on cond, exactly one is restarted, but it is not specified which.

pthread_cond_broadcast restarts all the threads that are waiting on the condition variable cond. Nothing happens if no threads are waiting on cond.

您的十个线程中的每一个都在相同的条件下等待。您只调用 go() 一次 - 来自 main()。这会调用 pthread_cond_signal,它只会向 一个 线程(任意一个)发出信号。所有其他人仍将等待,因此 pthread_join 挂起,因为它们不会终止。当您将其切换到 pthread_cond_broadcast 时, 所有 线程都会被触发。