C++ 提升 asio io_service dispatch vs post
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2326588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Boost asio io_service dispatch vs post
提问by coelhudo
Can anyone tell me the difference between io_service dispatchand post? It was not clear to me what is more suitable for my problem.
谁能告诉我 io_service dispatch和post之间的区别?我不清楚什么更适合我的问题。
I need to invoke a handler inside another handler and I don't know what invokerto use.
我需要在另一个处理程序中调用一个处理程序,但我不知道要使用什么调用程序。
回答by Macke
Well, it depends on the context of the call, i.e. is it run from within the io_service or without:
嗯,这取决于调用的上下文,即它是在 io_service 内运行还是不在:
post
will not call the function directly, ever, but postpone the call.dispatch
will call it rightaway if the dispatch-caller was called from io_service itself, but queue it otherwise.
post
永远不会直接调用该函数,而是推迟调用。dispatch
如果调度调用者是从 io_service 本身调用的,则将立即调用它,否则将其排队。
So, it depends on the function calling post/dispatch was called, and if the given handler can be called straight away or not.
因此,这取决于调用 post/dispatch 的函数,以及是否可以立即调用给定的处理程序。
What this means:
这是什么意思:
... is that dispatch
might eventually call your code again (naturally, this depends on your app and how you chain calls), but in general you should make sure your callback is re-entrant if you use dispatch
.
...dispatch
最终可能会再次调用您的代码(当然,这取决于您的应用程序以及您链接调用的方式),但一般而言,如果您使用dispatch
.
dispatch
is thus faster, as it avoids queueing the call if possible. It comes with some caveats, so you might want needs to use post
occasionally, or always (if you want to play it safe and can afford it).
dispatch
因此更快,因为它尽可能避免排队呼叫。它带有一些警告,因此您可能需要post
偶尔或始终使用(如果您想安全使用并且负担得起)。
Update
更新
To incorporate some from @gimpf 's deleted answer, an older boost version had this implementation of dispatch (my comments):
为了结合@gimpf 删除的答案中的一些内容,较旧的 boost 版本具有这种调度实现(我的评论):
template <typename Handler>
void dispatch(Handler handler)
{
if (call_stack<win_iocp_io_service>::contains(this)) // called from within io_service?
boost_asio_handler_invoke_helpers::invoke(handler, &handler); // invoke rightaway
else
post(handler); // queue
}
回答by Akira Takahashi
see this blog entry:
To post or to dispatch? - This Thread
请参阅此博客条目:
发布还是发送?- 这个主题
Running the application we'll see the difference between posting and dispatching. Since it could do it, dispatch() would execute fB() directly, so we'll see it runs in the current thread, and synchronously. On the other side, post() would ask to io_service to do the job, asynchronously in another thread, and it immediately returns the control to the caller.
运行应用程序,我们将看到发布和调度之间的区别。因为它可以做到,dispatch() 会直接执行 fB(),所以我们会看到它运行在当前线程中,并且是同步的。另一方面,post() 会要求 io_service 在另一个线程中异步完成这项工作,并且它立即将控制权返回给调用者。