如何等待多个事情 [英] How can I wait on multiple things

查看:202
本文介绍了如何等待多个事情的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C ++ 11和stl线程编写线程安全队列。 WaitAndPop方法当前如下所示。我想能够传递一些东西WaitAndPop,指示是否调用线程已被要求停止。 WaitAndPop应该返回true如果它等待并返回一个队列的元素,如果调用线程正在停止,它应该返回false。

I'm writing a thread safe queue using C++11 and stl threading. The WaitAndPop method currently looks like the following. I would like to be able to pass something to WaitAndPop that indicates if the calling thread has been asked to stop. WaitAndPop should return true if it waited for and returned an element of the queue, it should return false if the calling thread is being stopped.

    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,但是找不到适用于这种情况的替代方案。

Is it possible to code something like this? I'm used to a Win32 WaitForMultipleObjects, but can't find an alternative that works for this case.

谢谢。

我看到这个相关的问题,但它没有真正回答这个问题。 在linux上学习线程

I've seen this related question, but it didn't really answer the problem. learning threads on linux

推荐答案

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

If I understand your problem correctly, I would probably do something like this:

 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 作为变量名,因为它也是标准容器适配器的名称)。控制线程可以将停止设置为 true (同时持有 mutex )并调用 notifyOne() notifyAll() code>。

Here, stop is a global variable like condition and myQueue (I suggest not to use queue as a variable name, since it is also the name of a Standard container adapter). The controlling thread can set stop to true (while holding a lock to mutex) and invoke notifyOne() or notifyAll() on condition.

这样,通知***()停止信号被提出时,当新项目被推入队列时,在等待该条件变量之后,必须检查它被唤醒的原因并相应地采取行动。

This way, notify***() on the condition variable is invoked both when a new item is pushed into the queue and when the stop signal is being raised, meaning that a thread waking up after waiting on that condition variable will have to check for what reason it has been awaken and act accordingly.

这篇关于如何等待多个事情的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆