Monday, February 24, 2014

C++ thread-safe queue, two ways to implement

I just explored a little on this topic, how to implement thread safe queue.
The most standard method to introduce mutex and condition variable.

Take the problem of "to implement a thread-safe queue" as an example.

The idea is to lock the critical resource before operation, and release lock after. There are some terminologies, like "own the lock" means lock(); and "release" means unlock();

So, for the thread-safe queue, two operations need to implement are:
pop()
{
mutex.lock();
while(queue.empty())
{
condition_v.wait(mutex);
}
queue.pop();
mutex.unlock();
}

push(T &item)
{
mutex.lock();
queue.push(item);
mutex.unlock();
}

This is just pseudo-code above, for implementation, there are two different ways.
1. using pthread stuff. That is "piosix" API, which is a set of API in C style. For more details, please refer to:

The code for safe queue can be found here:


One thing worth to care about is "pthread_cond_wait(cond_v&, mutex&)" function will pass under the condition of "cond_v.signal() AND mutex.lock()", which means you must have cond_v be satisfied and own the lock. And at the begining of wait(...), it release the mutex. This can make sure other thread can access the critical resource. 


2. another way to implement this idea is to use new feature of C++ 11. 
A very good example is:

Where mutex.lock() can block in scope of block. I like this style, but really don't like that only lock(), but no unlock() operation.
They should show up as a pair naturally.