您能否从等待的互斥量中的不同互斥量发出条件变量信号?

Can you signal a condition variable from a different mutex from the one that is waiting?

例如,在伪代码中:

lock mutex1
pthread_cond_wait(condition, mutex1)
unlock mutex1

...来自另一个线程:

lock mutex2
pthread_cond_signal(condition)
unlock mutex2

调用线程是否必须锁定正在等待的同一个互斥量?在我看来,当您同时有许多线程 运行 想要相互通信时,这会限制条件变量的使用。

mutex2 与您的示例无关,您最好不要在通知程序中持有任何互斥量。

文档说:

pthread_cond_signal() may be called by a thread whether or not it currently owns the mutex that threads calling pthread_cond_wait() have associated with the condition variable during their waits; however, if predictable scheduling behavior is required, then that mutex shall be locked by the thread calling pthread_cond_broadcast() or pthread_cond_signal().

听起来您不需要任何特定的唤醒调度行为,所以是的,您可以在根本不持有任何互斥量的情况下或在持有不相关的互斥量时向条件变量发出信号。