条件变量[关闭]

问题描述 投票:4回答:1

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

synchronization operating-system condition-variable
1个回答
14
投票

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

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

/* 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 */

这个伪代码样本带有一个bug。如果调度程序决定在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);

希望能帮助到你。

© www.soinside.com 2019 - 2024. All rights reserved.