3

我正在使用 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上的学习线程

4

1 回答 1

9

如果我正确理解你的问题,我可能会做这样的事情:

 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;
}

这里,是一个像andstop这样的全局变量(我建议不要用作变量名,因为它也是一个标准容器适配器的名称)。控制线程可以设置为(同时持有对 的锁)并调用或on 。conditionmyQueuequeuestoptruemutexnotifyOne()notifyAll()condition

这样,在将新项目推入队列时和发出信号时都会notify***()调用条件变量,这意味着在等待该条件变量后唤醒的线程必须检查它被唤醒的原因并采取相应行动。stop

于 2013-03-28T18:07:52.817 回答