首页 > 其他 > 详细

Operating System: Three Easy Pieces --- Condition Variables (Note)

时间:2015-11-19 14:32:07      阅读:284      评论:0      收藏:0      [点我收藏+]

The other major component of any threads library, and certainly the case with POSIX threads, is

the presence of a condition variable. Condition variables are useful when some kind of signaling

must take place between threads, if one thread is waiting for another to do something before it

can continue. Two primary routines are used by programs wishing to interact in this way:

int pthread_cond_wait(pthread_cond_t* cond, pthread_mutex_t* mutex);
int pthread_cond_signal(pthread_cond_t* cond);

To use a condition variable, one has to in addition have a lock that is associated with this condition

. When calling either of the above routines this lock should be locked.

The first routine, pthread_cond_wait(), puts the calling thread to sleep, and thus waits for some 

other thread to signal it, usually when something in the program has changed that the now-

sleeping thread might care about. A typical usage looks like this:

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

pthread_mutex_lock(&lock);
while (ready == 0) {
        pthread_cond_wait(&cond, &wait);
}
pthread_mutex_unlock(&lock);

This is a placeholder.

Operating System: Three Easy Pieces --- Condition Variables (Note)

原文:http://www.cnblogs.com/miaoyong/p/4977316.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!