[英]How could a boost::asio::io_service running on 1 thread wake up awaiting condition
Thanks for you reply Sam Miller, but i need to implement it on windows. 谢谢您答复Sam Miller,但我需要在Windows上实现它。
Look at this example o wrote: 看这个例子o写道:
boost::mutex mut;
boost::condition_variable cond;
boost::asio::io_service io_service;
boost::asio::deadline_timer t(io_service);
void test_func()
{
boost::mutex::scoped_lock lk(mut);
cond.notify_all();
}
void cancel_test_func()
{
boost::unique_lock< boost::mutex > lk(mut);
auto canceled_timers = t.cancel();
cond.wait(lk);
printf("Canceled...%u.", canceled_timers);
}
int main(int argc, char* argv[])
{
try
{
t.expires_from_now(boost::posix_time::seconds(5));
t.async_wait(boost::bind(&test_func));
io_service.post(boost::bind(cancel_test_func));
boost::thread_group tg;
tg.create_thread( boost::bind(&boost::asio::io_service::run, &io_service) );
//tg.create_thread( boost::bind(&boost::asio::io_service::run, &io_service) );
getchar();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
To make this example works(cancel the timer) i need to uncomment the second thread creation. 为了使该示例工作(取消计时器),我需要取消对第二个线程创建的注释。 With only one thread, i never receive notification.
只有一个线程,我再也不会收到通知。 The question is: is this behavior normal?
问题是:这种行为正常吗?
A condition variable is a synchronous concept, it doesn't integrate well with an event loop like an io_service
. 条件变量是一个同步概念,无法与
io_service
这样的事件循环很好地集成。 If you want asynchronous events on Linux, look at eventfd(2)
with with EFD_SEMAPHORE
flag for semaphore semantics. 如果要在Linux上进行异步事件,请查看带有
EFD_SEMAPHORE
标志的eventfd(2)
,以获取信号量语义。 I'm not sure if there's an analogous interface on other platforms 我不确定其他平台上是否有类似的界面
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.