c#/ boost模拟的C#BlockingCollection?

jav*_*red 4 c++ boost

我喜欢C#线程安全BlockingCollection,它允许我使用TakeTryTake方法“阻止”直到有新项可用,例如,最大阻止时间为1秒:orderActions.TryTake(out oa, 1000);

什么是c ++ / boost模拟BlockingCollection

小智 5

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

或者,您可以使用此答案std::deque通过std::mutex和保护std::condition_variable(用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;
}    
Run Code Online (Sandbox Code Playgroud)

PeriodTstd::chrono::milliseconds例如,可以是。快速样本:

queue<int> p;
int v;
p.tryPop (v, std::chrono::milliseconds(1));
Run Code Online (Sandbox Code Playgroud)