Why pthread_cond_signal is deadlocked
I am new to conditional variables and get stumped if not using 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;
}
here the condition is changed
void go() {
pthread_mutex_lock(&m_mut);
ready = true;
pthread_mutex_unlock(&m_mut);
pthread_cond_signal(&cv);
}
It can work if I change the last line go()
topthread_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;
}
Expected response (arbitrary order)
thread 0
....
thread 9
However on my machine (ubuntu) it doesn't print anything. Can anyone tell me the reason? Thank.
source to share
From the man page (with my emphasis):
pthread_cond_signal
restarts one of the threads waiting for a condition variablecond
. If thecond
thread doesn't wait, nothing happens. Ifcond
multiple threads are expected, then one of them is restarted, but which is not specified.
pthread_cond_broadcast
restarts all threads waiting on a condition variablecond
. Nothing happens if the threads don't wait oncond
.
Each of your ten threads is expecting the same state. You only call go()
once - from main()
. This calls pthread_cond_signal
to only signal one of the threads (arbitrary). Everyone else will still be waiting, and hence pthread_join
freezes as they will not complete. When you switch it to pthread_cond_broadcast
, all threads are started.
source to share