c++ - Basic usage of conditionals with std::atomic<T> -
so i'm starting familiarize myself c++11 <atomic> types. in past, when had atomic flag lock mutex before accessing it. mutual need check if flag false, , if so, atomically set true , something. accomplished this, flag simple bool:
{ std::lock_guard<std::mutex> lock(my_mutex); if (!flag) { flag = true; // something; } } so, i'm trying figure out how same thing can accomplished <atomic>. docs assignment operator , operator t of atomic type atomic operations. however, if alter flag std::atomic<bool>, imagine can't simple say:
if (!flag) { flag = true; // } ... because though look (!flag) atomic, , assignment flag = true atomic, there's nil prevent thread modifying flag in between 2 statements.
so, if understand correctly here, proper usage - at all - of conditionals atomic types, result of conditional modify atomic variable, utilize compare , swap operation? correct?
so, i'd have say:
bool expected = false; if (flag.compare_exchange_weak(expected, true)) { // } am right in understanding here?
if have multiple threads running same code need flip, yes - need utilize compare_exchange_weak() or compare_exchange_strong() exactly reason suggest (probably prefer strong).
however, it's not case only proper usage of conditionals atomics. if have, say, 1 thread ever reads atomic , 1 writes it, it's reasonable utilize them simple way... e.g.:
std::atomic<bool> done{false}; // thread 1 while (!done) { .... } // thread 2 stop() { done = true; } there's no reason me done.compare_exchange_strong(expected, true) there. that's overkill. it's on case-by-case basis.
c++ c++11 atomic
No comments:
Post a Comment