简体   繁体   中英

why use std::atomic if it still requires a mutex to work properly

Reading the text for std::condition_variable I've come across this sentence:

Even if the shared variable is atomic, it must be modified under the mutex in order to correctly publish the modification to the waiting thread.

My question is this:

What is the use for atomics if not for "lock-free code to work with PODs"?

UPDATE

Looks like there's some confusion about my question :(

The "shared variable" in the quoted text is not the same as "condition variable". See this quote from the same page:

... until another thread both modifies a shared variable (the condition), and notifies the condition_variable

Please do not answer " why we need to use a mutex with condition variables " or " how the conditional wait works " but rather provide information on how the use of a mutex "correctly publishes" the modification of an atomic to the waiting thread, ie whether an expression like ++counter; ( not the test like if(counter == 0) ) would need to be done under mutex?

The semantics of a conditional wait necessitates the use of a mutex.

This is because there is a potential race condition on the thread that is testing the condition. When this thread is checking whether to wait, the following happens:

  1. acquire exclusive lock
  2. perform the test
  3. either:

    a) release lock and wait for next signal

    b) keep lock and continue

Because step 1 acquires a lock, the whole thing is atomic, provided all other parties use the mutex correctly.

But what about when the variable being modified is an atomic?

Even if the shared variable is atomic, it must be modified under the mutex in order to correctly publish the modification to the waiting thread.

Well, here's why. If thread B comes along and modifies the atomic outside of the mutex, then steps 2 and 3 are no longer atomic. Essentially, thread B can modify the value immediately after step 2 happens. Then thread A will potentially make an incorrect decision in step 3.

why use std::atomic if [condition variable] still requires a mutex to work properly

There is no reason to use an atomic condition variable.

What is the use for atomics

Even if atomics aren't useful for condition variables, they can still be useful for other use cases. A typical use case for atomics is implementation of a lock free queue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM