如果线程调用 pthread_cond_wait(cond_ptr,mutex_ptr) 将返回一个null cond_ptr,是否保证不会睡着?
根据 http://pubs.opengroup.org/onlinepubs/007908799/xsh/pthread_cond_wait.html , 一个空的 cond_ptr 只是意味着 pthread_cond_wait() 可能(不是强调的将)失败,所以我猜线程可以在空条件变量上睡着?
最佳答案
我看不到一个有效的用例,我想知道为什么它会很重要。您不应该使用无效的条件变量调用pthread_cond_wait
。
如果您担心它,只需更改您的代码:
pthread_cond_wait (pcv, pmutex);
类似于:
if (pcv != NULL) pthread_cond_wait (pcv, pmutex);
并且不会用 NULL 调用它。
我怀疑它被写成“可能”只是因为有一个 pthreads 的实现(甚至可能是原始的 DEC 线程本身)在这种情况下没有返回失败代码。
但是,由于几乎可以肯定的是整个事情都变成了尖叫的一堆,所以我不会依赖它 :-)
如果您担心该代码的原子性,则大可不必。只需使用保护条件变量的相同互斥锁来保护列表中保存的 CV 指针:
claim mutex A
somenode->cv = NULL
release mutex A
并且,在您的循环代码中:
claim mutex A
if loopnode->cv != null:
wait on condvar loopnode->cv using mutex A
// mutex A is locked again
: : :
互斥量在 if
和调用 pthread_condvar_wait
期间都被锁定的事实意味着不存在竞争条件。在循环线程释放 pthread_condvar_wait
调用中的互斥锁之前,没有任何东西可以更改节点条件变量。到那时,该调用将使用它自己的指针本地副本,因此更改列表中的一个将不会有任何效果。
并且,如果更改节点的代码获取了互斥锁,则在释放该互斥锁之前,if
和 pthread_condvar_wait
无法执行。
关于c - pthread_cond_wait 的空参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5166613/