Browse Source

Semaphore - use std::<atomic> types for thread synchronization. (otherwise undef behaviour)

pull/5/head
heck 2 years ago
parent
commit
64b6857bd2
1 changed files with 11 additions and 5 deletions
  1. +11
    -5
      Semaphore.hh

+ 11
- 5
Semaphore.hh View File

@ -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 <atomic> types
std::atomic_bool _stop;
public:
Semaphore() : _stop(false) { }
@ -13,23 +17,25 @@ namespace pEp {
void stop()
{
std::unique_lock<std::mutex> lock(mtx);
_stop = true;
_stop.store(true);
}
void try_wait()
{
std::unique_lock<std::mutex> lock(mtx);
if (!_stop)
if (_stop.load() == false) {
return;
}
while(_stop)
while(_stop.load() == true) {
cv.wait(lock);
}
}
void go()
{
std::unique_lock<std::mutex> lock(mtx);
_stop = false;
_stop.store(false);
cv.notify_all();
}
};


Loading…
Cancel
Save