diff --git a/Semaphore.hh b/Semaphore.hh index e7d3f06..400e081 100644 --- a/Semaphore.hh +++ b/Semaphore.hh @@ -5,7 +5,11 @@ namespace pEp { class Semaphore { std::mutex mtx; std::condition_variable cv; - bool _stop; + // Atomic types are types that encapsulate a value whose access is guaranteed + // to not cause data races and can be used to synchronize memory accesses among + // different threads. + // To synchronize threads, ALWAYS use types + std::atomic_bool _stop; public: Semaphore() : _stop(false) { } @@ -13,23 +17,25 @@ namespace pEp { void stop() { std::unique_lock lock(mtx); - _stop = true; + _stop.store(true); } void try_wait() { std::unique_lock lock(mtx); - if (!_stop) + if (_stop.load() == false) { return; + } - while(_stop) + while(_stop.load() == true) { cv.wait(lock); + } } void go() { std::unique_lock lock(mtx); - _stop = false; + _stop.store(false); cv.notify_all(); } };