条件变量应该用作等待和通知的地方。它们不是条件本身,也不是事件。条件包含在周围的编程逻辑中。条件变量的典型用法是
// safely examine the condition, prevent other threads from// altering itpthread_mutex_lock (&lock);while ( SOME-ConDITION is false) pthread_cond_wait (&cond, &lock);// Do whatever you need to do when condition becomes truedo_stuff();pthread_mutex_unlock (&lock);
另一方面,发出信号通知条件变量的线程通常看起来像
// ensure we have exclusive access to whathever comprises the conditionpthread_mutex_lock (&lock);ALTER-CONDITION// Wakeup at least one of the threads that are waiting on the condition (if any)pthread_cond_signal (&cond);// allow others to proceedpthread_mutex_unlock (&lock)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)