条件变量Condition Variable的一般用法:
唤醒用法:
1 struct { 2 pthread_mutex_t mutex; 3 pthread_cond_t cond; 4 //whatever variables maintain the condition 5 ) var = { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, ... };//声明结构体并初始化 6 7 pthread_mutex_lock(&var.mutex); 8 //set condition true 9 pthread_cond_signal(&var.cond): 10 pthread_mutex_unlock(&var.mutex);
等待用法:
1 pthread_mutex_lock(&var.mutex); 2 while (/*condition is false*/) 3 pthread_cond_wait(&var.cond, &var.mutex); 4 //modify condition 5 pthread_mutex_unlock(&var.mutex);
避免锁冲突:
有一种情况是,唤醒线程中调用pthread_cond_signal之后,假如立即调度等待线程。那么等待线程立即运行然后停止,因为它不能获取到锁。为了不影响等待线程及时获取锁,唤醒线程另一种写法是:
1 int dosignal; 2 pthread_mutex_lock(&nready.mutex); 3 dosignal = (nready.nready == 0); 4 nready.nready++; 5 pthread_mutex_unlock(&nready.mutex); 6 7 //先释放锁,然后唤醒等待线程 8 if (dosignal) 9 pthread_cond_signal(&nready.cond);
即,先释放锁,然后唤醒。这样就避免了等待线程请求锁的冲突问题。而调用pthread_cond_wait之前必须加锁。
时间: 2024-12-19 07:33:32