Skip to content
Permalink
Browse files

Handle spurious wakeups on worker thread condition variables properly

  • Loading branch information...
CookiePLMonster committed Aug 10, 2019
1 parent 6ac41a5 commit 0639ffcfb52c86722fc718fc854ce0818711fc34
Showing with 11 additions and 3 deletions.
  1. +11 −3 ext/native/thread/threadpool.cpp
@@ -27,7 +27,7 @@ void WorkerThread::Process(std::function<void()> work) {

void WorkerThread::WaitForCompletion() {
std::unique_lock<std::mutex> guard(doneMutex);
if (jobsDone < jobsTarget) {
while (jobsDone < jobsTarget) {
done.wait(guard);
}
}
@@ -37,7 +37,11 @@ void WorkerThread::WorkFunc() {
std::unique_lock<std::mutex> guard(mutex);
started = true;
while (active) {
signal.wait(guard);
// 'active == false' is one of the conditions for signaling,
// do not "optimize" it
while (active && jobsTarget <= jobsDone) {
signal.wait(guard);
}
if (active) {
work_();
doneMutex.lock();
@@ -67,7 +71,11 @@ void LoopWorkerThread::WorkFunc() {
std::unique_lock<std::mutex> guard(mutex);
started = true;
while (active) {
signal.wait(guard);
// 'active == false' is one of the conditions for signaling,
// do not "optimize" it
while (active && jobsTarget <= jobsDone) {
signal.wait(guard);
}
if (active) {
work_(start_, end_);
doneMutex.lock();

0 comments on commit 0639ffc

Please sign in to comment.
You can’t perform that action at this time.