progschj / ThreadPool

A simple C++11 Thread Pool implementation
zlib License
7.63k stars 2.21k forks source link

possible deadlock during ~ThreadPool #115

Open ShunlongHu opened 1 month ago

ShunlongHu commented 1 month ago

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 commented 1 month ago

image

faywong commented 2 weeks ago

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();