Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 )

like image 391
Damir Avatar asked Jul 27 '12 11:07

Damir


2 Answers

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.

like image 52
Mike Seymour Avatar answered Sep 22 '22 10:09

Mike Seymour


Here is a pseudo code:

// Thread A
mutex.lock();
q.push();
mutex.unlock();

// Thread B
mutex.lock();
q.pop();
mutex.unlock();

If you're using boost, you may try it's mutex class.

like image 39
Donotalo Avatar answered Sep 24 '22 10:09

Donotalo