C# BlockingCollection 的 c++/boost 模拟?

标签 c++ boost

我喜欢 C# 线程安全的 BlockingCollection,它允许我使用 Take “阻塞”直到新项目可用TryTake 方法,例如最多阻止 1 秒:orderActions.TryTake(out oa, 1000);

BlockingCollection 的 c++/boost 模拟是什么?

最佳答案

你可以使用 boost::lockfree库以实现所需的行为。 在这种情况下,您可以在 pop 方法之上实现 TakeTryTake

或者您可以使用 this answerstd::mutexstd::condition_variable 保护 std::deque(用 C++11 编写的答案,但你可以使用 boost::thread 访问来自旧编译器的线程相关内容)。

更新

实际上我不推荐第一种方法因为它扼杀了无锁容器的整个想法:) 所以,对于第二种情况TryTake (tryPop)可以用下面的代码实现(只是例子)

template<typename PeriodT>
bool tryPop (T & v, PeriodT dur) {
    std::unique_lock<std::mutex> lock(this->d_mutex);
    if (!this->d_condition.wait_for(lock, dur, [=]{ return !this->d_queue.empty(); })) {
        return false;
    }
    v = std::move (this->d_queue.back());
    this->d_queue.pop_back();
    return true;
}    
例如,

PeriodT 可以是 std::chrono::milliseconds。快速示例:

queue<int> p;
int v;
p.tryPop (v, std::chrono::milliseconds(1));

关于C# BlockingCollection 的 c++/boost 模拟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19043638/

相关文章:

c++ - 如何确保返回 vector <unique_ptr> 的常量

c++ - 如何通过 Boost.MPI 发送 2d Boost.MultiArray 的子数组?

c++ - 如何编写没有任何字母但只能使用主词的c代码?

c++ - Callgrind 内联函数

c++ - 使用 MinGW 检查 Boost 安装

c++ - 你如何添加两个 boost 任何值?

c++ - Boost文档声明

c++ - 发生哪些线程异步操作

c++ - 如何在 cpp 中将 uint8_t[][] 转换为 char[]

c++ - 在 C++ 中转换对象