pthread_cond_broadcast 之后哪个线程拥有关联的互斥体?

Which thread owns the associated mutex after pthread_cond_broadcast?

此问题涉及 Posix 系统的 pthread API。

我的理解是,在等待条件变量时,或者更具体地说是 pthread_cond_t,流程是这样的。

// imagine the mutex is named mutex and the conditional variable is named cond

// first we lock the mutex to prevent race conditions
pthread_mutex_lock(&mutex);

// then we wait for the conditional variable, releasing the mutex
pthread_cond_wait(&cond, &mutex);

// after we're done waiting we own the mutex again have to release it
pthread_mutex_unlock(&mutex);

在这个例子中,当其他线程遵循这样的过程时,我们停止等待互斥体。

// lock the mutex to prevent race conditions
pthread_mutex_lock(&mutex);

// signal the conditional variable, giving up control of the mutex
pthread_cond_signal(&cond);

我的理解是,如果多个线程正在等待,将应用某种调度策略,并且无论哪个线程被解除阻塞,也会取回关联的互斥量。

现在我不明白是当某个线程调用pthread_cond_broadcast(&cond)唤醒所有线程时会发生什么等待条件变量。

是否只有一个线程拥有互斥锁?等待广播与等待信号时是否需要以根本不同的方式等待(即不调用 pthread_mutex_unlock 除非我可以确认该线程获得了互斥体)?或者我对 mutex/cond 关系如何运作的整个理解是错误的?

最重要的是,如果(我认为可能是这种情况)pthread_cond_broadcast 导致线程竞争关联的互斥锁,就好像它们都试图锁定它一样,那是否意味着只有一个线程会真正醒来?

当某个线程在持有互斥量的同时调用 pthread_cond_broadcast 时,它持有互斥量。这意味着一旦 pthread_cond_broadcast returns,它仍然拥有互斥量。

其他线程将全部唤醒,尝试锁定互斥锁,然后进入休眠等待互斥锁可用。

如果您调用 pthread_cond_broadcast 没有 持有互斥锁,那么其他线程之一将能够立即锁定互斥锁。所有其他人都必须等待锁定互斥体。