Atomic <bool> vs bool protected by mutex

Suppose we have a memory area in which some stream writes data. Then he turns his attention to another place and allows arbitrary other threads to read data. However, at some point in time, he wants to reuse this area of ​​memory and write it again.

A logical flag ( valid) is supplied in the write stream , which indicates that the memory remains valid for reading (i.e. it does not reuse it yet). At some point, he will set this flag to false and never return it to true (he just changes it once and that’s it).

With consistent consistency, it should be correct to use these two code snippets for the writer and readers, respectively:

...
valid = false;
<write to shared memory>
...

and

...
<read from shared memory>
if (valid) {
    <be happy and work with data read>
} else {
    <be sad and do something else>
}
...

, , - , , . , false , , . , , valid. , , , , - , .

valid . , , valid ?

std::atomic<bool> valid = true;

...
valid.store(false); // RELEASE
<write to shared memory>
...

...
<read from shared memory>
if (valid.load()) { // ACQUIRE
    <be happy and work with data read>
} else {
    <be sad and do something else>
}
...

, . RELEASE ( ). , ACQUIRE ( ).

, , ACQUIRE ( ) , RELEASE (.. ) . ( ) . , ACQUIRE, RELEASE , valid .

, atomic<bool> bool, mutex, ?

. , . std::atomic ++ 11 memory_order_seq_cst (!), memory_order_acquire memory_order_release .

, tbb::atomic memory_semantics::acquire memory_semantics::release, memory_semantics::full_fence.

, , ++ 11, tbb memory_semantics::full_fence .

+4
1

valid false , .

, , .

++ , undefined.

- std::shared_mutex, .

+1

All Articles