dispatch icon indicating copy to clipboard operation
dispatch copied to clipboard

About condition usage

Open dourgulf opened this issue 8 years ago • 1 comments

I thinks, condition.notify_one() must be call in mutex lock scope. Why you try to avoid it? (usage reference :http://en.cppreference.com/w/cpp/thread/condition_variable)

void thread_pool::push_task_with_priority(const dispatch::function& task, queue::priority priority) {
    {
        std::unique_lock<std::mutex> lock(mutex);

        auto queue = queues[priority];
        if (!queue) {
            queue = std::make_shared<queue_impl>(priority);
            queues[priority] = queue;
        }
        
        queue->tasks.push(task);
        
        unsigned max_number_of_threads = std::max<unsigned>(std::thread::hardware_concurrency(), 2);
        unsigned number_of_threads_required = round(log(queues.size()) + 1);
        while (threads.size() < std::min<unsigned>(max_number_of_threads, number_of_threads_required)) {
            add_worker();
        }
    }
    condition.notify_one();
}

dourgulf avatar Mar 20 '17 03:03 dourgulf

If condition.notify_one not in mutext lock scope, the worker thread may be start the task before condition.notify_one was called. And the worker thread loop in next time, it try to wait, and will be await by that notify_one signal.

dourgulf avatar Mar 20 '17 04:03 dourgulf