我怎么能等这么多事情呢
How can I wait on multiple things
本文关键字:怎么能 更新时间:2023-10-16
我正在使用c++ 11和stl线程编写线程安全队列。WaitAndPop方法目前看起来如下所示。我希望能够传递一些东西给WaitAndPop,指示是否调用线程已被要求停止。如果WaitAndPop等待并返回队列的一个元素,它应该返回true,如果调用线程正在停止,它应该返回false。
bool WaitAndPop(T& value, std::condition_variable callingThreadStopRequested)
{
std::unique_lock<std::mutex> lock(mutex);
while( queuedTasks.empty() )
{
queuedTasksCondition.wait(lock);
}
value = queue.front();
queue.pop_front();
return true;
}
有可能编写这样的代码吗?我习惯了Win32的WaitForMultipleObjects,但找不到适合这种情况的替代方案。
谢谢。
我看过这个相关的问题,但它并没有真正回答这个问题。linux上的学习主题
如果我正确理解你的问题,我可能会这样做:
bool WaitAndPop(T& value)
{
std::unique_lock<std::mutex> lk(mutex);
// Wait until the queue won't be empty OR stop is signaled
condition.wait(lk, [&] ()
{
return (stop || !(myQueue.empty()));
});
// Stop was signaled, let's return false
if (stop) { return false; }
// An item was pushed into the queue, let's pop it and return true
value = myQueue.front();
myQueue.pop_front();
return true;
}
这里,stop
是像condition
和myQueue
一样的全局变量(我建议不要使用queue
作为变量名,因为它也是标准容器适配器的名称)。控制线程可以将stop
设置为true
(同时持有mutex
的锁),并在condition
上调用notifyOne()
或notifyAll()
。
这样,当一个新项目被推入队列时,条件变量上的notify***()
被调用,当stop
信号被引发时,被调用,这意味着在等待该条件变量后唤醒的线程将不得不检查它被唤醒的原因并相应地采取行动。
相关文章:
- Arduino millis() - millis() 怎么能等于 0 以外的任何东西?
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 我们怎么能 me 字符数组只接受 C++ 中的字母
- 你怎么能emplace_back错误的类型?
- 我怎么能有一个以2D数组为参数的函数,而数组有一个我想更改的参数/维度
- 我怎么能把它转换成c++呢
- 我有一个调用ID3D11DeviceContext::CopySubresourceRegion的循环.我怎么能强制等待
- 类定义怎么能不占用内存?
- 怎么能用memcpy复制工会简单的成员?
- 当 do-while 再次启动时,对象将被删除.我怎么能阻止它
- 指针怎么能有一个字符串作为它的值
- 一个函数怎么能完成它的目标,只是在返回主函数后崩溃?
- 这两个指针怎么能有相同的值
- glTranslatef拉伸我的球体,我怎么能不拉伸它就平移球体
- 我怎么能像 numpy 那样从 MxN 矩阵中减去 1xN 特征矩阵
- 我怎么能写一个长度函数来返回间隔的长度
- 我怎么能设法从我的代码中获得复数的答案
- 我怎么能在不使用BITSet的情况下知道C 中的位状态
- 如果指针已经被删除,指针容器怎么能拥有指针的所有权
- 如果 npos 为 -1,size_type怎么能成为无符号积分