简体   繁体   English

如何在队列原子上进行推送和弹出,如何锁定这些操作?

[英]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 ) 如何在队列原子上进行推送和弹出,如何锁定那些操作?(我不能使用C ++ 11标准)

Probably the most portable non-C++11 locking mechanism is are the synchronisztion types from the Boost.Thread library. 可移植性最强的非C ++ 11锁定机制可能是Boost.Thread库中的同步类型。 In particular the mutex class gives you a simple lockable object for giving exclusive access to a resource. 特别是, mutex类为您提供了一个简单的可锁定对象,用于提供对资源的独占访问。 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. 另一个优点是,这与C ++ 11 std::mutex类非常相似,如果您决定使用它,这将使转换变得非常简单。

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. 如果你正在使用boost,你可以试试它的互斥类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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