From 64b6857bd2c93536db316f7aeed83af89aab04ca Mon Sep 17 00:00:00 2001 From: heck Date: Tue, 16 Feb 2021 00:49:08 +0100 Subject: [PATCH] Semaphore - use std:: types for thread synchronization. (otherwise undef behaviour) --- Semaphore.hh | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) 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(); } };