c++ - Synchronizing access to data using a "got there first" flag, instead of a lock/mutex -
suppose have function accesses globally shared data - , suppose function called multiple concurrent threads.
naturally, need somehow synchronize access data. possible via mechanism have atomic flag, , whichever thread manages set flag can proceed access shared data? whereas losing threads not block on lock, return function.
something following:
given globally shared data along synchronization flag:
namespace global { int x; int y; std::atomic_flag sync_flag = atomic_flag_init; }
and our function accessed concurrent threads:
void race() { // see if won race // if (!global::sync_flag.test_and_set()) { // won // global::x = 10; global::y = 11; } else { // lost... return; } }
does above code guarantee global::x
, global::y
safely accessed single thread, , no race conditions occur? or not guaranteed due memory ordering problems?
note never locked mutex or anything, no thread ends blocking. idea here ensure 1 thread allowed access (non-atomic) global variables here.
of course, after winning thread done, need somehow safely clear atomic flag if ever intend on calling race()
again. problem haven't thought yet, beyond scope of question.
so above code race-condition free (for single call race()
)?
yes. 1 thread can not-yet-set test on flag. has advantage on mutex in on architectures atomic flag can done lock-free operations.
Comments
Post a Comment