Do condition variables still need a mutex if you're changing the checked value atomically?

前端 未结 1 689
时光说笑
时光说笑 2021-02-05 12:56

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_         


        
相关标签:
1条回答
  • 2021-02-05 13:37

    Imagine the following scenario:

    | 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);                    |                                                    |
    

    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.)

    0 讨论(0)
提交回复
热议问题