相关疑难解决方法(0)

C++相当于Java的BlockingQueue

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

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

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

我已经google了一下,并迅速浏览了Boost库,我找不到这样的东西.也许我在这里失明了......但有人知道一个好推荐吗?

谢谢!

c++ multithreading

30
推荐指数
2
解决办法
2万
查看次数

创建阻塞队列

有时,这种实施和执行BlockingQueue确实有效。有时会出现段错误。知道为什么吗?

#include <thread>
using std::thread;
#include <mutex>
using std::mutex;
#include <iostream>
using std::cout;
using std::endl;
#include <queue>
using std::queue;
#include <string>
using std::string;
using std::to_string;
#include <functional>
using std::ref;

template <typename T>
class BlockingQueue {
private:
    mutex mutex_;
    queue<T> queue_;
public:
    T pop() {
        this->mutex_.lock();
        T value = this->queue_.front();
        this->queue_.pop();
        this->mutex_.unlock();
        return value;
    }

    void push(T value) {
        this->mutex_.lock();
        this->queue_.push(value);
        this->mutex_.unlock();
    }

    bool empty() {
        this->mutex_.lock();
        bool check = this->queue_.empty();
        this->mutex_.unlock();
        return check;
    }
};

void fillWorkQueue(BlockingQueue<string>& workQueue) …
Run Code Online (Sandbox Code Playgroud)

c++ multithreading blockingqueue c++11

2
推荐指数
1
解决办法
1万
查看次数

标签 统计

c++ ×2

multithreading ×2

blockingqueue ×1

c++11 ×1