我怎么能等这么多事情呢

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是像conditionmyQueue一样的全局变量(我建议不要使用queue作为变量名,因为它也是标准容器适配器的名称)。控制线程可以将stop设置为true(同时持有mutex的锁),并在condition上调用notifyOne()notifyAll()

这样,当一个新项目被推入队列时,条件变量上的notify***()被调用,当stop信号被引发时,被调用,这意味着在等待该条件变量后唤醒的线程将不得不检查它被唤醒的原因并相应地采取行动。