问题描述
是否可以对boost :: asio中的条件变量执行异步等待(读取:非阻塞)?如果它不是直接支持任何提示实现它将不胜感激。
Is it possible to perform an asynchronous wait (read : non-blocking) on a conditional variable in boost::asio ? if it isn't directly supported any hints on implementing it would be appreciated.
我可以实现一个定时器和唤醒,甚至每几个毫秒,但这是方法是非常差,我发现很难相信条件变量同步没有实现/记录。
I could implement a timer and fire a wakeup even every few ms, but this is approach is vastly inferior, I find it hard to believe that condition variable synchronization is not implemented / documented.
推荐答案
如果我正确理解了意图,那么当一个条件变量被发出时, asio线程池?我认为在处理程序的开头等待条件变量就足够了,本身返回到池中,这是这样的:
If I understand the intent correctly, you want to launch an event handler, when some condition variable is signaled, in context of asio thread pool? I think it would be sufficient to wait on the condition variable in the beginning of the handler, and io_service::post() itself back in the pool in the end, something of this sort:
#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
boost::asio::io_service io;
boost::mutex mx;
boost::condition_variable cv;
void handler()
{
boost::unique_lock<boost::mutex> lk(mx);
cv.wait(lk);
std::cout << "handler awakened\n";
io.post(handler);
}
void buzzer()
{
for(;;)
{
boost::this_thread::sleep(boost::posix_time::seconds(1));
boost::lock_guard<boost::mutex> lk(mx);
cv.notify_all();
}
}
int main()
{
io.post(handler);
boost::thread bt(buzzer);
io.run();
}
这篇关于boost asio异步等待条件变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!