关于condition variable的理解

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">最近在学习多线程的时候遇到了一个问题,那就是在使用conditions进行同步时,需要加锁。文档中给出的代码如下。</span>
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Multithreading/ThreadSafety/ThreadSafety.html#//apple_ref/doc/uid/10000057i-CH8-124690
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">这是第一个线程的,</span>

pthread_mutex_t mutex;
pthread_cond_t condition;
Boolean     ready_to_go = true;
 
void MyCondInitFunction()
{
    pthread_mutex_init(&mutex);
    pthread_cond_init(&condition, NULL);
}
 
void MyWaitOnConditionFunction()
{
    // Lock the mutex.
    pthread_mutex_lock(&mutex);
 
    // If the predicate is already set, then the while loop is bypassed;
    // otherwise, the thread sleeps until the predicate is set.
    while(ready_to_go == false)
    {
        pthread_cond_wait(&condition, &mutex);
    }
 
    // Do work. (The mutex should stay locked.)
 
    // Reset the predicate and release the mutex.
    ready_to_go = false;
    pthread_mutex_unlock(&mutex);
}
这是第二个线程的

void SignalThreadUsingCondition()
{
    // At this point, there should be work for the other thread to do.
    pthread_mutex_lock(&mutex);
    ready_to_go = true;
 
    // Signal the other thread to begin work.
    pthread_cond_signal(&condition);
 
    pthread_mutex_unlock(&mutex);
}


最开始碰到了这个问题:使用conditions即可,为何还要使用一个ready_to_go变量呢?

这个问题在文档中写的很清楚,Due to the subtleties involved in implementing operating systems, condition locks are permitted to return with spurious success even if they were not actually signaled by your code. To avoid problems caused by these spurious signals, you should always use a predicate in conjunction with your condition lock. The predicate is a more concrete way of determining whether it is safe for your thread to proceed. The condition simply keeps your thread asleep until the predicate can be set by the signaling thread. 就是说使用condition目前实现时有一些问题,会产生spurious signals,因此要结合一个predicate,就是断言信号来确定,这里就是ready_to_go。

还有一个问题,就是为何两个线程都使用了同一个互斥锁,这样第一个线程使用锁时,岂不是第二个线程永远无法唤醒第一线程了么?

后来查看文档点击打开链接,知道了These functions atomically release mutex and cause the calling thread to block on the condition variable cond;。就是说调用函数pthread_cond_wait 会使当前线程释放互斥锁,然后被condition variable阻塞。点击打开链接 pthread_cond_signalt会使持有condition variable的线程唤醒,然后这些(一个活多个)线程就会争抢互斥锁,争抢到互斥锁的就会继续执行,其他(如果有)线程就会被阻塞。至于为何在调用pthread_cond_signalt时需要加互斥锁呢?这是为了把改变spurious signals的值和调用pthread_cond_signal做为原子操作来看待。

因此,在第二个线程的互斥锁释放后,第一个线程才会争抢互斥锁。

下起雨,也要勇敢前行
原文地址:https://www.cnblogs.com/huahuahu/p/5877631.html