ThreadPool icon indicating copy to clipboard operation
ThreadPool copied to clipboard

possible deadlock during ~ThreadPool

Open ShunlongHu opened this issue 1 year ago • 6 comments

condition.notify_all(); should be enclosed in the brack of unique_lock. This is to ensure that all workers are either waiting or executing while notify_all command is dispatched.

ShunlongHu avatar May 24 '24 02:05 ShunlongHu

image

ShunlongHu avatar May 24 '24 02:05 ShunlongHu

So as the enqueue() method:


     std::future<return_type> res = task->get_future();
    {
        std::unique_lock<std::mutex> lock(queue_mutex);

        // don't allow enqueueing after stopping the pool
        if(stop)
            throw std::runtime_error("enqueue on stopped ThreadPool");

        tasks.emplace([task](){ (*task)(); });
    } // here
    condition.notify_one();

faywong avatar Jun 18 '24 01:06 faywong

I don't see this causing a deadlock

XiaomingQu0913 avatar Jul 17 '24 07:07 XiaomingQu0913

I don't see this causing a deadlock

All workers should not be within critical section when cv.notify_all is dispatched. Otherwise, the workers may miss the notify_all.

ShunlongHu avatar Jul 17 '24 08:07 ShunlongHu

Although not notified, this->tasks is not empty, so it will not sleep the next time it enters thecritical section.

XiaomingQu0913 avatar Jul 17 '24 09:07 XiaomingQu0913

this is even what cppreference suggested: https://en.cppreference.com/w/cpp/thread/condition_variable I quote:

manual unlocking is done before notifying, to avoid waking up the waiting thread only to block again (see notify_one for details)

Toby-Shi-cloud avatar Dec 10 '24 18:12 Toby-Shi-cloud