Update Thread.cpp
Fixed a bug that caused a race between ~Thread and Thread::Runner receiving a new job from the threadpool
This commit is contained in:
@@ -49,6 +49,5 @@ public:
|
|||||||
|
|
||||||
/// Waits for the threads to empty the queue and destroys the thread pool.
|
/// Waits for the threads to empty the queue and destroys the thread pool.
|
||||||
/// @note This should be one of the very last things your program does before exiting.
|
/// @note This should be one of the very last things your program does before exiting.
|
||||||
// TODO make Enqueue fail during destruction to avoid stalls.
|
|
||||||
~ThreadPool();
|
~ThreadPool();
|
||||||
};
|
};
|
@@ -5,13 +5,19 @@
|
|||||||
using namespace MultiThreading;
|
using namespace MultiThreading;
|
||||||
|
|
||||||
Thread::~Thread() {
|
Thread::~Thread() {
|
||||||
if (current_task)
|
std::shared_ptr<TaskBase> task;
|
||||||
current_task->WaitComplete();
|
|
||||||
stop = true;
|
|
||||||
|
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mtx);
|
||||||
|
task = current_task;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (task)
|
||||||
|
task->WaitComplete();
|
||||||
|
|
||||||
|
stop = true;
|
||||||
cv.notify_one();
|
cv.notify_one();
|
||||||
Join();
|
Join();
|
||||||
// Thread exits gracefully.
|
|
||||||
}
|
}
|
||||||
|
|
||||||
bool Thread::SetTask(std::shared_ptr<TaskBase> task) {
|
bool Thread::SetTask(std::shared_ptr<TaskBase> task) {
|
||||||
@@ -43,9 +49,10 @@ void Thread::Runner() {
|
|||||||
if (stop)
|
if (stop)
|
||||||
break;
|
break;
|
||||||
|
|
||||||
|
auto task = current_task;
|
||||||
lock.unlock();
|
lock.unlock();
|
||||||
|
|
||||||
current_task->Run();
|
task->Run();
|
||||||
|
|
||||||
lock.lock();
|
lock.lock();
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user