On 21-Mar-17 5:56 AM, kushal bhattacharya wrote:
> hi,
> I have onw question regarding the implementation.
> Are you putting the lock when you are enquiring for size of queue in the while loop ?
Yes. Here's that code:
Lock lock{ q.m_mutex };
while( q.m_queue.size() == 0 )
{
q.m_cond.wait( lock );
}
return lock; // It's moved.
The declaration of lock acquires the mutex; it's now locked.
Next, the while loop condition, checking the queue size, is evaluated,
with the mutex acquired. Only one thread can have it at a time, and
right now it's this thread.
The `q.m_cond.wait( lock )` statement then releases the mutex, opening
up for other threads to access the queue. In particular, to push items
onto it. When that `wait` returns it acquires the mutex again. And so in
the next iteration of the loop, if there is one, the mutex is again held
by this thread when the queue size is checked, and so on, and on.
Finally the `return` /moves/ the lock back up to the caller of this
function. The `std::unique_lock` guarantees its move semantics, that the
locking is actually moved.
You can find documentation of these details at <url:
http://cppreference.com>.
Cheers!,
- Alf