Skip to content

About condition usage #1

Open
Open

Description

@dourgulf

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

Activity

  1. dourgulf commented on Mar 20, 2017

    @dourgulf
    Author

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions