pthread_cond_init.man:源码内容中的介绍
A condition variable must always be associated with a mutex, to avoid
the race condition where a thread prepares to wait on a condition
variable and another thread signals the condition just before the
first thread actually waits on it.
条件变量必须配合锁来使用,来避免如下的竞争条件:一个线程准备在条件变量上等待,但是进入等待之前另一个线程唤醒了条件变量。
也就是说,没有锁进行同步的情况下,一个线程在wait操作中被挂起,并没有完成wait,这时另一个线程触发了signal操作进行唤醒,然后第一个线程才完成wait操作,那第一个线程就收不到第二个线程的signal操作。
所以,根据上边的解释,通过锁使wait和signal操作进行线程同步,通过锁使wait和signal都是原子操作。
相关函数:
#include <pthread.h>
int pthread_cond_init(pthread_cond_t *cond, pthread_condattr_t *cond_attr);
int pthread_cond_signal(pthread_cond_t *cond);
int pthread_cond_broadcast(pthread_cond_t *cond);
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime);
int pthread_cond_destroy(pthread_cond_t *cond);