C ++相当于Java的BlockingQueue [英] C++ Equivalent to Java's BlockingQueue

查看:130
本文介绍了C ++相当于Java的BlockingQueue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一些Java代码移植到C ++,一个特定的部分使用BlockingQueue将消息从许多生产者传递给单个消费者。

I'm in the process of porting some Java code over to C++, and one particular section makes use of a BlockingQueue to pass messages from many producers to a single consumer.

如果你不熟悉Java BlockingQueue是什么,它只是一个具有硬容量的队列,这暴露了线程安全的方法put()和take()从队列。如果队列已满,则为put()块,如果队列为空,则为take()块。此外,还提供了这些方法的超时敏感版本。

If you are not familiar with what a Java BlockingQueue is, it is just a queue that has a hard capacity, which exposes thread safe methods to put() and take() from the queue. put() blocks if the queue is full, and take() blocks if the queue is empty. Also, timeout-sensitive versions of these methods are supplied.

超时与我的用例相关,因此提供这些方法的建议是理想的。如果没有,我可以自己编写一些代码。

Timeouts are relevant to my use-case, so a recommendation that supplies those is ideal. If not, I can code up some myself.

我已经google了,快速浏览了Boost库,我找不到这样的。也许我在这里...但是有谁知道一个好的建议?

I've googled around and quickly browsed the Boost libraries and I'm not finding anything like this. Maybe I'm blind here...but does anyone know of a good recommendation?

谢谢!

推荐答案

它不是固定的大小,它不支持超时,但这里是一个队列我最近发布的一个简单的实现使用C ++ 2011构造:

It isn't fixed size and it doesn't support timeouts but here is a simple implementation of a queue I had posted recently using C++ 2011 constructs:

#include <mutex>
#include <condition_variable>
#include <deque>

template <typename T>
class queue
{
private:
    std::mutex              d_mutex;
    std::condition_variable d_condition;
    std::deque<T>           d_queue;
public:
    void push(T const& value) {
        {
            std::unique_lock<std::mutex> lock(this->d_mutex);
            d_queue.push_front(value);
        }
        this->d_condition.notify_one();
    }
    T pop() {
        std::unique_lock<std::mutex> lock(this->d_mutex);
        this->d_condition.wait(lock, [=]{ return !this->d_queue.empty(); });
        T rc(std::move(this->d_queue.back()));
        this->d_queue.pop_back();
        return rc;
    }
};

扩展和使用时间等待弹出应该是微不足道的。我没有做的主要原因是,我不满意我迄今为止所想到的接口选择。

It should be trivial to extend and use a timed wait for popping. The main reason I haven't done it is that I'm not happy with the interface choices I have thought of so far.

这篇关于C ++相当于Java的BlockingQueue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆