提升::亚洲.确保仅在调用async_receive(..)后调用io_service.run()?
BOOST::ASIO. Making sure io_service.run() is invoked only after async_receive(...) is called?
>我有一个问题,两个线程像这样一个接一个地调用。
new boost::thread( &SERVER::start_receive, this);
new boost::thread( &SERVER::run_io_service, this);
第一个线程调用此函数的位置。
void start_receive()
{
udp_socket.async_receive(....);
}
和第二个线程调用,
void run_io_service()
{
io_service.run();
}
有时io_service
线程最终会在start_receive()
线程之前完成,然后服务器无法接收数据包。
我想过在两个线程之间放置一个睡眠函数以等待一段时间以完成start_receive()
并且有效,但我想知道是否有另一种确定的火方法可以实现这一目标?
当你调用io_service.run()
时,线程将阻塞,调度已发布的处理程序,直到:
-
没有与
io_service
相关联的io_service::work
对象,或者 -
io_service.stop()
被称为。
如果发生上述任一情况,io_service
将进入停止状态,并将拒绝在将来调度任何更多的处理程序,直到调用其reset()
方法。
每次对与io_service关联的 io 对象启动异步操作时,异步处理程序中都会嵌入一个 io_service::work 对象。
因此,在异步处理程序运行之前,上面的 (1) 点无法发生。
因此,此代码将保证异步过程完成,并且断言通过:
asio::io_service ios; // ios is not in stopped state
assert(!ios.stopped());
auto obj = some_io_object(ios);
bool completed = false;
obj.async_something(..., [&](auto const& ec) { completed = true; });
// nothing will happen yet. There is now 1 work object associated with ios
assert(!completed);
auto ran = ios.run();
assert(completed);
assert(ran == 1); // only 1 async op waiting for completion.
assert(ios.stopped()); // io_service is exhausted and no work remaining
ios.reset();
assert(!ios.stopped()); // io_service is ready to run again
如果要保持io_service
运行,请创建一个work
对象:
boost::asio::io_service svc;
auto work = std::make_shared<boost::asio::io_service::work>(svc);
svc.run(); // this will block as long as the work object is valid.
这种方法的好处是,上面的work
对象将使svc
对象保持"运行",但不会阻止对其执行任何其他操作。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- Seg Fault Issue C++ (file IO / getline)
- 为什么使用 "this" 指针调用派生成员函数?
- 函数调用中参数的顺序重要吗
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在c++类上调用void函数
- 为什么 std::unique 不调用 std::sort?
- 调用专用模板时出错"no matching function for call to [...]"
- 选择要调用的构造函数
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- C++为什么尽管我调用了void函数,它却不起作用
- 构造函数正在调用一个使用当前类类型的函数
- C++ 中的文件 IO 出错。在抛出 'std::length_error' 的实例后调用的终止 what(): basic_string::调整大小
- CPP 建议更好的方法在没有开销/IO 调用的情况下进入静音状态
- 在同一语句中调用的执行 IO 的函数:未定义或未指定
- 调用WP 8(C#)中的WinRT组件时出现System.IO.FileNotFoundException错误
- 没有系统或IO调用的睡眠