Skip to content

Commit

Permalink
Try a different a approach at terminating the threads.
Browse files Browse the repository at this point in the history
  • Loading branch information
dfalbel committed Nov 6, 2024
1 parent 48534ad commit ce0f46f
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions inst/include/utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,13 @@ class EventLoop {
{
std::unique_lock<std::mutex> lock(mtx_);
if (tasks_.empty()) {
cv_.wait(lock, [this] { return !tasks_.empty(); });
cv_.wait(lock, [this] { return stop_requested_ || !tasks_.empty(); });
}

if (stop_requested_ && tasks_.empty()) {
return;
}

fn = std::move(tasks_.front());
tasks_.pop_front();
}
Expand All @@ -76,10 +81,15 @@ class EventLoop {
}
cv_.notify_one();
}
void stop() {
stop_requested_ = true;
cv_.notify_all();
}

private:
std::mutex mtx_;
std::condition_variable cv_;
std::atomic<bool> stop_requested_{false};
std::deque<std::packaged_task<T()>> tasks_;
};

Expand All @@ -99,9 +109,9 @@ class ThreadPool {
this->event_loop.schedule(std::move(task));
}
~ThreadPool() {
this->event_loop.stopWhenEmpty();
event_loop.stop();
for(auto& thread : threads) {
thread.detach();
thread.join();
}
}
};
Expand Down

0 comments on commit ce0f46f

Please sign in to comment.