linux 条件变量

    xiaoxiao2021-12-14  17

    转自:linux 条件变量与互斥锁

    条件变量,与锁不同, 条件变量用于等待某个条件被触发

    基本编写的代码如下:

    // 线程一代码 ================================================= pthread_mutex_lock(&mutex); // 设置条件为true ... 操作 pthread_cond_signal(&cond);  // 条件满足时通过线程二 pthread_mutex_unlock(&mutex); // 线程二代码 ================================================= pthread_mutex_lock(&mutex); while (条件为false)     pthread_cond_wait(&cond, &mutex); // 永久或超时等待线程一通知条件满足 修改该条件 ... 操作 pthread_mutex_unlock(&mutex); 需要注意几点:

    1) 第二段代码之所以在pthread_cond_wait外面包含一个while循环不停测试条件是否成立的原因是, 在pthread_cond_wait被唤醒的时候可能该条件已经不成立.

    UNPV2对这个的描述是:

    "Notice that when pthread_cond_wait returns, we always test the condition again, because spurious wakeups can occur: a wakeup when the desired condition is still not true.".

    2) pthread_cond_wait调用必须和某一个mutex一起调用, 这个mutex是在外部进行加锁的mutex, 在调用pthread_cond_wait时, 内部的实现将首先将这个mutex解锁, 然后等待条件变量被唤醒, 如果没有被唤醒, 该线程将一直休眠, 也就是说, 该线程将一直阻塞在这个pthread_cond_wait调用中, 而当此线程被唤醒时, 将自动将这个mutex加锁.

    man文档中对这部分的说明是:

    pthread_cond_wait atomically unlocks the mutex (as per pthread_unlock_mutex) and waits for the condition variable cond to  be  signaled.  The thread execution is suspended and does not consume any CPU time until the condition variable is

    signaled. The mutex must be locked by the calling thread on entrance to pthread_cond_wait.  Before  returning  to  the calling thread, pthread_cond_wait re-acquires mutex (as per pthread_lock_mutex).

    也就是说pthread_cond_wait实际上可以看作是以下几个动作的合体: 解锁线程锁 等待条件为true 加锁线程锁.
    转载请注明原文地址: https://ju.6miu.com/read-963223.html

    最新回复(0)