6

条件变量在操作系统进程同步中的原理是什么?

4

1 回答 1

14

好吧,条件变量允许您等待某些条件发生。在实践中,您的线程可能会在条件变量上休眠,而其他线程会将其唤醒。

条件变量通常也带有互斥锁。这使您可以解决以下同步问题:如何检查某些受互斥锁保护的数据结构的状态,然后等到它的状态更改为其他状态。IE

/* in thread 1 */
pthread_mutex_lock(mx); /* protecting state access */
while (state != GOOD) {
    pthread_mutex_unlock(mx);
    wait_for_event();
    pthread_mutex_lock(mx);
}
pthread_mutex_unlock(mx);


/* in thread 2 */
pthread_mutex_lock(mx); /* protecting state access */
state = GOOD;
pthread_mutex_unlock(mx);
signal_event(); /* expecting to wake thread 1 up */

这个伪代码示例带有一个错误。如果调度程序决定在 pthread_mutex_unlock(mx) 之后但在 wait_for_event() 之前将上下文从线程 1 切换到线程 2,会发生什么情况。在这种情况下,线程 2 不会唤醒线程 1,而线程 1 将继续休眠,可能永远。

条件变量通过在睡眠前原子地解锁互斥锁并在醒来后原子地锁定它来解决这个问题。有效的代码如下所示:

/* in thread 1 */
pthread_mutex_lock(mx); /* protecting state access */
while (state != GOOD) {
    pthread_cond_wait(cond, mx); /* unlocks the mutex and sleeps, then locks it back */
}
pthread_mutex_unlock(mx);

/* in thread 2 */
pthread_mutex_lock(mx); /* protecting state access */
state = GOOD;
pthread_cond_signal(cond); /* expecting to wake thread 1 up */
pthread_mutex_unlock(mx);

希望能帮助到你。

于 2011-04-21T23:23:31.083 回答