From 9094154d460d8f01fe3a3748d1cd366ce893e63b Mon Sep 17 00:00:00 2001 From: heck Date: Mon, 28 Feb 2022 23:29:32 +0100 Subject: [PATCH] Import: module 'Semaphore' from libpEpAdapter --- src/Semaphore.hh | 51 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 src/Semaphore.hh diff --git a/src/Semaphore.hh b/src/Semaphore.hh new file mode 100644 index 0000000..c026185 --- /dev/null +++ b/src/Semaphore.hh @@ -0,0 +1,51 @@ +// This file is under GNU General Public License 3.0 +// see LICENSE.txt + +#ifndef LIBPEPADAPTER_SEMAPHORE_HH +#define LIBPEPADAPTER_SEMAPHORE_HH + +#include +#include +#include + +namespace pEp { + class Semaphore { + std::mutex mtx; + std::condition_variable cv; + // 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) {} + + void stop() + { + std::unique_lock lock(mtx); + _stop.store(true); + } + + void try_wait() + { + std::unique_lock lock(mtx); + if (!_stop.load()) { + return; + } + + while (_stop.load()) { + cv.wait(lock); + } + } + + void go() + { + std::unique_lock lock(mtx); + _stop.store(false); + cv.notify_all(); + } + }; +} // namespace pEp + +#endif // LIBPEPADAPTER_SEMAPHORE_HH