简体   繁体   中英

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 )

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM