If a thread calls pthread_cond_wait(cond_ptr,mutex_ptr) will a null cond_ptr, is it guaranteed to not fall asleep?
According to http://pubs.opengroup.org/onlinepubs/007908799/xsh/pthread_cond_wait.html, a null cond_ptr just means pthread_cond_wait() may (not an emphatic will) fail, so I guess threads can then fall asleep 开发者_开发问答on null condition variables?
I can't see a valid use case for this and I'm wondering why it would ever matter. You shouldn't be calling pthread_cond_wait
with an invalid condition variable.
If you're worried about it, just change your code from:
pthread_cond_wait (pcv, pmutex);
to something like:
if (pcv != NULL) pthread_cond_wait (pcv, pmutex);
and it won't be called with a NULL.
I suspect it was put in as "may" simply because there was an implementation of pthreads (perhaps even the original DEC threads itself) which didn't return a failure code for that circumstance.
But, since the alternative is almost certainly that the whole thing fell in a screaming heap, I wouldn't be relying on it :-)
If you're worried about the atomicity of that code, you needn't be. Simply use the same mutex that protects the condition variable to protect the CV pointer being held in your list:
claim mutex A
somenode->cv = NULL
release mutex A
and, in your looping code:
claim mutex A
if loopnode->cv != null:
wait on condvar loopnode->cv using mutex A
// mutex A is locked again
: : :
The fact that the mutex is locked during both the if
and calling pthread_condvar_wait
means that no race condition can exist. Nothing can change the node condition variables until the looping thread releases the mutex within the pthread_condvar_wait
call. And by that time, the call is using its own local copy of the pointer so changing te one in the list will have no effect.
And, if the node-changing code grabs the mutex, the if
and pthread_condvar_wait
can't execute until that mutex is released.
精彩评论