In the context of interfacing some QT GUI thread (a pthread thread) with some C code, I stumbled over the following problem: I launch the QT Gui thread and, before my C thread resuming its path, I need to make sure that all the graphical objects inside the QT Gui thread had been constructed and they are valid QObjects (since the C code will call QObject:connect() on those).
Introduction let aside, the waiting is made through a pthread_cond_wait() + a condition variable + an associated mutex in the C thread:
int isReady=0;
pthread_mutex_lock(&conditionReady_mutex);
while(isReady==0) {
pthread_cond_wait(&conditionReady_cv, &conditionReady_mutex);
}
pthread_mutex_unlock(&conditionReady_mutex);
On the other hand, the QT Gui thread constructs its graphical objects and then signals it with:
pthread_mutex_lock(&conditionReady_mutex);
isReady=1;
pthread_cond_broadcast(&conditionReady_cv);
pthread_mutex_unlock(&conditionReady_mutex);
Basic stuff, as you see. But the question is: in the Qt Gui thread, I’ve been using the pthread_cond_broadcast(), in order to make sure that my C thread is woken up, for sure. Yes, in my current application, I only have a C thread and a Qt Gui thread, and pthread_cond_signal() should do the job of waking up the C thread (since it is guaranteed to wake up at least one thread, and the C thread is the only one).
But, in a more general context, let’s say I have three C threads, but I want one (or two) of them to be woken up. A (two) specific thread(s). How do I ensure that?
If I use pthread_cond_signal(), that could simply wake up only the third thread, which would completely miss the point, since the one thread of interest for me is not woken up. OTOH, waking up all the threads, even those which are unneeded, through pthread_cond_broadcast(), that would be overkill.
There is a way to tell pthread_cond_signal() which thread to wake up?
Or, should I introduce more condition variables in order to have a finer granularity over the groups of threads that are woken up with pthread_cond_broadcast()?
Thank you.
Yes, if you require a specific thread to be woken up then you either need to broadcast the wakeup, or use a separate condition variable for that thread.