如果您要自动更改检查值,条件变量是否仍需要互斥锁? [英] Do condition variables still need a mutex if you're changing the checked value atomically?
问题描述
以下是使用条件变量的典型方法:
Here is the typical way to use a condition variable:
// The reader(s)
lock(some_mutex);
if(protected_by_mutex_var != desired_value)
some_condition.wait(some_mutex);
unlock(some_mutex);
// The writer
lock(some_mutex);
protected_by_mutex_var = desired_value;
unlock(some_mutex);
some_condition.notify_all();
但是,如果通过比较和交换指令自动设置了protected_by_mutex_var,那么互斥锁是否有任何用途(除了pthread和其他API要求您传递互斥锁外)?它是用于执行条件的保护状态吗?如果不是,那么这样做安全吗?:
But if protected_by_mutex_var is set atomically by say, a compare-and-swap instruction, does the mutex serve any purpose (other than that pthreads and other APIs require you to pass in a mutex)? Is it protecting state used to implement the condition? If not, is it safe then to do this?:
// The writer
atomic_set(protected_by_mutex_var, desired_value);
some_condition.notify_all();
作者永远不会与读者的互斥体直接互动吗?请注意,'protected_by_mutex_var'名称不再是真正合适的名称(不再受互斥保护).如果是这样,甚至有必要让不同的读者使用相同的互斥锁吗?
With the writer never directly interacting with the reader's mutex? Note that the 'protected_by_mutex_var' name is no longer really appropriate (it's not mutex protected anymore). If so, is it even necessary that different readers use the same mutex?
推荐答案
想象一下以下情况:
| Thread 1 | Thread 2 |
| if(protected_by_mutex_var != desired_value) -> true | |
| | atomic_set(protected_by_mutex_var, desired_value); |
| | some_condition.notify_all(); |
| some_condition.wait(some_mutex); | |
这种情况下,线程1正在等待可能永远不会到来的通知. 由于作用于条件的语句不属于变量read/atomic集合的一部分,因此这表示竞争条件.
This situation sees Thread 1 waiting for a notify that may never come. Because the statements acting on the condition are not part of the variable read / atomic set, this presents a race condition.
有效地使用互斥锁会使这些动作不可分割(假设对变量的所有访问均正常运行并锁定了互斥锁.)
Using the mutex effectively makes these actions inseparable (assuming all accesses to the variable behave properly and lock the mutex.)
这篇关于如果您要自动更改检查值,条件变量是否仍需要互斥锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!