我正在使用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,但是找不到适合这种情况的替代方法。

谢谢。

我已经看到了这个相关的问题,但是并没有真正回答这个问题。 learning threads on 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的锁定),并在notifyOne()上调用notifyAll()condition

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

10-06 09:05
查看更多