pthread_singal awakes more than one thread on a multiprocessor system
This is an excerpt from pthread_cond_wait man page Some implementations, particularly on a multi-processor, may sometimes cause multiple threads to wake up when the condition variable is signaled simultaneously on different processors.
In general, whenever a condition wait returns, the thread has to re-evaluate the predicate associated with the condition wait to determine whether it can safely proceed, should wait again, or should declare a timeout. My Question: here what is the meaning of predicate?Does it mean that I need to create one more variable apart from the conditional variable provided in pthread_cond_wait or does it referring to the same variable which ha开发者_JAVA技巧s been provided in pthread_cond_wait
Yes, you need an additional variable like int done_flag;
to use like this:
pthread_mutex_lock(&mutex);
while (!done_flag) pthread_cond_wait(&cond, &mutex);
/* do something that needs the lock held */
pthread_mutex_unlock(&mutex);
/* do some other stuff that doesn't need the lock held */
Of course it often might not be a flag but rather a count, or some other type of variable, with a more complicated condition to test.
This might be useful. You can use pthread_kill to wake a particular thread.
sigset_t _fSigMask; // global sigmask
We do this before creating our threads. Threads inherit their mask from the thread that creates them. We use SIGUSR1 to signal our threads. Other signals are available.
sigemptyset(&_fSigMask);
sigaddset(&_fSigMask, SIGUSR1);
sigaddset(&_fSigMask, SIGSEGV);
Then to sleep a thread
int nSig;
sigwait(&fSigMask, &nSig);
Then to wake the thread, YourThread.
pthread_kill(YourThread, SIGUSR1);
By the way, during our testing, sleeping and waking our threads this way was about 40x faster than using condition variables.
精彩评论