当 pthread_cond_broadcast 被调用并且多个线程被唤醒只是为了竞争同一个互斥锁时会发生什么?

What happens when pthread_cond_broadcast is called and multiple threads are awoken only to compete for the same mutex?

当您调用 pthread_cond_broadcast() 并且多个线程醒来只是为了竞争同一个互斥锁时会发生什么。其中一个线程获取了互斥锁,但其他线程发生了什么?他们回去睡觉了吗?或者他们会旋转直到锁再次可用?

What happens when you call pthread_cond_broadcast() and multiple threads wake up just to compete for the same mutex lock. One of the threads takes the mutex lock but what happens to the other threads? Do they go back to sleep? Or do they spin until the lock is available again?

当您调用 pthread_cond_broadcast() 时,所有等待指定条件变量的线程都会停止。所有这些线程都将向 pthread_cond_wait() 传递(指向)相同的互斥锁,否则行为未定义。每个未阻塞的线程在从 pthread_cond_wait() 成功返回之前将(重新)获取该互斥体。这可能需要它们中的一些甚至全部进行阻塞,就好像它们在任何其他情况下都在争夺同一个互斥体一样。它们不旋转,并且它们不需要与 CV 进行任何进一步的交互就可以恢复,但是当它从 pthread_cond_wait() returns 时,每个人都会保持互斥锁锁定,就像它调用时一样那个函数。