请教有关条件变量cond是如何使用的,具体用来干吗的?谢谢

来源:百度知道 编辑:UC知道 时间:2024/05/29 16:02:15
我已经知道mutex的使用方法,但是我不清楚条件变量是用来干什么的?
如pthread_cond_wait和pthread_cond_broadcast是干什么的?
最好形象的讲下原理,我用man查看时,发现没讲条件变量是用来做什么的
谢谢

这个问题在UNIX高级环境编程中有深刻的讲解,我这里是从英文版中摘抄过来的,你可以用心看一下 :)

Condition variables are another synchronization mechanism available to threads. Condition variables provide a place for threads to rendezvous. When used with mutexes, condition variables allow threads to wait in a race-free way for arbitrary conditions to occur.

The condition itself is protected by a mutex. A thread must first lock the mutex to change the condition state. Other threads will not notice the change until they acquire the mutex, because the mutex must be locked to be able to evaluate the condition.

Before a condition variable is used, it must first be initialized. A condition variable, represented by the pthread_cond_t data type, can be initialized in two ways. We can assign the constant PTHREAD_COND_INITIALIZER to a statically-allocated condition variable, but if the condition variable is allocated dynamically, we can use the pthread_cond_init function to initialize it.

We can