Browse Source

fix race condition

rebrand
Martin Dørum 3 years ago
parent
commit
4babe1483d
1 changed files with 9 additions and 11 deletions
  1. 9
    11
      src/parallel.cc

+ 9
- 11
src/parallel.cc View File

@@ -11,7 +11,6 @@ struct Worker {
bool running;
std::function<void(void)> func;
std::condition_variable cond;
std::mutex mut;

std::thread thread;
Worker *next_worker;
@@ -27,21 +26,23 @@ static int num_threads = 0;
static int waiting = 0;

static void workerFunc(Worker *w) {
std::unique_lock<std::mutex> lock(w->mut);
while (true) {
std::unique_lock<std::mutex> lock(workers_mut);
w->cond.wait(lock, [w] { return (bool)w->func || !w->running; });
if (!w->running)
break;

lock.unlock();
w->func();
lock.lock();

w->func = nullptr;
std::unique_lock<std::mutex> workers_lock(workers_mut);
w->next_worker = head;
head = w;
workers_lock.unlock();
workers_cond.notify_one();

threads_running -= 1;
lock.unlock();
workers_cond.notify_one();
}
}

@@ -65,13 +66,10 @@ ParallelContext::~ParallelContext() {
Worker *w = head;
while (w) {
w->running = false;
lock.unlock();
w->cond.notify_one();
w = w->next_worker;
}

w = head;
while (w) {
w->thread.join();
lock.lock();
w = w->next_worker;
}

@@ -103,10 +101,10 @@ void run(std::function<void(void)> func) {
head = head->next_worker;
threads_running += 1;
waiting -= 1;
lock.unlock();

// Launch!
w->func = std::move(func);
lock.unlock();
w->cond.notify_one();
}


Loading…
Cancel
Save