How to make push and pop on queue atomic, how to lock those operations?

boost, c++, multithreading, queue, stl

Solution

Probably the most portable non-C++11 locking mechanism is are the synchronisztion types from the Boost.Thread library. In particular the mutex class gives you a simple lockable object for giving exclusive access to a resource. For example:

#include <boost/thread/mutex.hpp>
#include <queue>

template <typename T>
class locking_queue {
public:
    void push(T const & value) {
        boost::mutex::scoped_lock lock(mutex);
        queue.push(value);
    }

    bool pop(T & value) {
        boost::mutex::scoped_lock lock(mutex);
        if (queue.empty()) {
            return false;
        } else {
            value = queue.front();
            queue.pop();
            return true;
        }
    }

private:
    std::queue<T> queue;
    boost::mutex mutex;
};

Another advantage is that this is quite similar to the C++11 `std::mutex` class, which will make conversion quite straightforward if you decide to use that instead.

Problem

I am using queue for communication between two threads ( one just producing instance of custom class and pushes pointer to queue, other read from queue pointer on custom class and make some calculations). How to make push and pop on queue atomic, how to lock those operations ?( I cannot use C++11 standard )

Original source