Thread: Make Barrier reusable
This commit is contained in:
parent
8c50833445
commit
3c710f9b10
1 changed files with 5 additions and 5 deletions
|
@ -69,20 +69,19 @@ private:
|
||||||
|
|
||||||
class Barrier {
|
class Barrier {
|
||||||
public:
|
public:
|
||||||
explicit Barrier(size_t count_) : count(count_), waiting(0) {}
|
explicit Barrier(size_t count_) : count(count_), waiting(0), generation(0) {}
|
||||||
|
|
||||||
/// Blocks until all "count" threads have called Sync()
|
/// Blocks until all "count" threads have called Sync()
|
||||||
void Sync() {
|
void Sync() {
|
||||||
std::unique_lock<std::mutex> lk(mutex);
|
std::unique_lock<std::mutex> lk(mutex);
|
||||||
|
const size_t current_generation = generation;
|
||||||
// TODO: broken when next round of Sync()s
|
|
||||||
// is entered before all waiting threads return from the notify_all
|
|
||||||
|
|
||||||
if (++waiting == count) {
|
if (++waiting == count) {
|
||||||
|
generation++;
|
||||||
waiting = 0;
|
waiting = 0;
|
||||||
condvar.notify_all();
|
condvar.notify_all();
|
||||||
} else {
|
} else {
|
||||||
condvar.wait(lk, [&]{ return waiting == 0; });
|
condvar.wait(lk, [this, current_generation]{ return current_generation != generation; });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -91,6 +90,7 @@ private:
|
||||||
std::mutex mutex;
|
std::mutex mutex;
|
||||||
const size_t count;
|
const size_t count;
|
||||||
size_t waiting;
|
size_t waiting;
|
||||||
|
size_t generation; // Incremented once each time the barrier is used
|
||||||
};
|
};
|
||||||
|
|
||||||
void SleepCurrentThread(int ms);
|
void SleepCurrentThread(int ms);
|
||||||
|
|
Loading…
Reference in a new issue