【问题标题】:Use of timed_wait from boost?从 boost 中使用 timed_wait?
【发布时间】:2012-03-27 07:44:19
【问题描述】:

我正在尝试使用来自 boost 的timed_wait。现在我其实不太清楚该怎么做。

整个事情的目的是确定它的状态。在下面的代码中调用了函数getStatus()。这个函数是异步的,如果一切正常,它会调用一个特定的回调函数来指示一切正常。如果它没有及时调用回调(所以发生超时)我知道出了点问题。

下面是示例代码:

void myClass::checkStatus()
{
    boost::mutex::scoped_lock lock(m_Mutex);
    boost::condition_variable cond;
    while(true)
    {
        getStatus();  // Async Call to get the actual status
        if(!cond.timed_wait(lock,boost::posix_time::milliseconds(3000),/* Callback */))
        { 
           // Timeout
        }
        else
        {
            // OK 
        }
    }
}
bool myClass::myCallback()
{
/* ... */
}

所以,如您所见,我不知道如何适当地将回调“添加”到我的 timed_wait。实际上我并没有真正了解它是如何工作的,因为我希望我的回调是从我的异步线程而不是从 timed_wait 本身调用的? (异步线程需要表明一切顺利)

我也查看了Boost Documentation,但它帮不了我更多。

关于第二个问题:我在这个例子中的互斥锁是否总是被锁定..?

【问题讨论】:

    标签: c++ boost boost-thread


    【解决方案1】:

    关于您的第二个问题:在执行timed_wait 期间,互斥锁被锁定在整个checkStatus 函数except 中。这就是关键。

    我不确定您对myCallback 的意图是什么。但要检查状态,我将向myClass 添加一个状态成员,将其设置在getStatus 中,然后在timed_waitelse 分支中检查它。一个例子:

    boost::condition_variable m_cond;
    
    void myClass::checkStatus()
    {
        boost::mutex::scoped_lock lock(m_Mutex);
    
        while(true)
        {
            getStatus();  // Async Call to get the actual status
            if(!m_cond.timed_wait(lock,boost::posix_time::milliseconds(3000),/* Callback */))
            { 
               // Timeout
            }
            else
            {
                //check status
                if (m_status == STATUS_1)
                {
                    // handle STATUS_1
                }
                else if (m_status == STATUS_2)
                {
                    // handle STATUS_2
                }
             }
        }
    }
    
    void getStatus()
    {
        boost::thread myThread(myWorkerFunc);  
    }
    
    void myWorkerFunc()
    {
        // do a long running operation to get the status
        int status = retrieveStatusSomehow();
    
        // lock the same mutex that you used for the condition variable
        boost::mutex::scoped_lock lock(m_Mutex);
    
        // assign the status to member
        m_status = status;
    
        // notify the condition to wake up
        m_cond.notify_all();
    }
    

    我希望现在更清楚了。也许您可以在这种方法中集成您的回调函数。此外,您应该考虑在超时的情况下取消后台线程以避免竞争条件。

    编辑:请注意,条件变量必须是一个成员,以通知它异步操作的结束。

    【讨论】:

    • 好吧,我想我明白了....我会尝试调整你的方法..虽然我有点感觉我得到 boost timed_wait 的目的是错误的(最初我在寻找 @ 987654331@ - 好吧,现在就试试你的建议
    • 好的问题:除了超时,timed_wait 会阻塞多长时间?直到它可以解锁给定的锁或直到 notify_all() 被调用?
    • 这是个好问题。在调用notify_allnotify_one 之前,它会被锁定。它还可以在spurious wakups 上解除阻塞(上面的代码不是处理的)
    • 好的,这对我来说真的很划算!它现在可以工作了(修改了你的代码)!谢谢!!!
    猜你喜欢
    • 2011-10-28
    • 1970-01-01
    • 2011-02-16
    • 2020-07-03
    • 1970-01-01
    • 1970-01-01
    • 2020-11-17
    • 2011-06-07
    • 1970-01-01
    相关资源
    最近更新 更多