Search code examples
c++multithreadingthread-safetymutexcondition-variable

Extraneous call to unlock on scoped_lock


In the following blogpost:

http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html

There is a 'push' method defined as follows:

void push(Data const& data)
{
   boost::mutex::scoped_lock lock(the_mutex);
   the_queue.push(data);
   lock.unlock();
   the_condition_variable.notify_one();
}

My questions are:

  1. why is there an explicit 'lock.unlock()' being called upon the scoped_lock variable?

  2. What is its purpose?

  3. Can it be safely removed, resulting in the 'notify_one' method call be within the scope of the scoped_mutex?


Solution

  • The unlock is not necessary. It might reduce the time that the mutex is locked for slightly, however.

    Keeping it or removing it will not affect thread safety or result in deadlocks.

    EDIT: As the article mentions, however, leaving the unlock in there can result in less contention on the mutex. You might as well leave it in. Alternatively, use scope around the mutex, which I personally find highlights the scope of the mutex better if glancing at the code.