Sco*_*ham 3 c++ multithreading stl c++11
我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)
是否可以编写这样的代码?我已经习惯了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;
}
Run Code Online (Sandbox Code Playgroud)
这里stop是一个像condition和的全局变量myQueue(我建议不要queue用作变量名,因为它也是标准容器适配器的名称).控制线程可以设置stop为true(同时保持锁定mutex)并调用notifyOne()或notifyAll()打开condition.
通过这种方式,notify***()在条件变量调用这两个新项目时被推入队列和当stop信号被提高,这意味着一个线程等待这个条件变量起床后必须检查它已被唤醒什么原因并采取相应行动.