我正在尝试使用来自 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但它对我帮助不大。
关于第二个问题:在这个例子中我的互斥量是否总是被锁定......?
最佳答案
关于你的第二个问题:在timed_wait
执行期间,互斥量在整个checkStatus
函数except中被锁定。这就是关键。
我不确定您对 myCallback
的意图是什么。但是要检查状态,我会向 myClass
添加一个状态成员,在 getStatus
中设置它并在 的
。一个例子:else
分支中检查它>timed_wait
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();
}
我希望现在更清楚了。也许您可以在这种方法中集成您的回调函数。此外,您还应该考虑在超时情况下取消后台线程以避免出现竞争情况。
编辑:请注意,条件变量必须是通知它异步操作结束的成员。
关于c++ - 使用boost的timed_wait?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9885305/