Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

c++ - boost::io_service How to guarantee handler execution sequence

I have a thread pool with boost::io_service on top. I use it for different CPU-bound tasks in whole application. For some tasks, I have to guarantee that tasks will be executed in specified order (decoding video stream). Using io_service::strand guaranties that tasks will not be executed currently, but it has no guarantee about the order of execution. In other words, task #5 may be executed before task #4. Is there any method to solve that problem, other than scheduling next task after executing of current.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

strand provides both the guarantee of not executing completion handlers concurrently and defines the order of handler invocation. In short, completion handlers posted into a strand are executed in the same order in which they are posted.

Therefore:

strand_.post(&task1);
strand_.post(&task2);
strand_.post(&task3);

Guarantees order of handler invocation is task1 -> task2 -> task3. However, wrapped completion handlers for asynchronous operations are not guaranteed, as the order in which asynchronous operations are performed is unspecified. For example, the following does not provide the same guarantee:

async_read(socket1, ..., strand_.wrap(&task1));
async_read(socket2, ..., strand_.wrap(&task2));
async_read(socket3, ..., strand_.wrap(&task3));

If completion handlers must be invoked in a specified order for asynchronous operations, then either:

  • Queue completion handlers and manage the order manually.
  • Serialize all asynchronous operations. For example, async_op_1's completion handler task1 initiates async_op_2 with a completion handler of task2.

Here is the relevant excerpt from io_service::strand's order of handler invocation documentation:

Given:

  • a strand object s
  • an object a meeting completion handler requirements
  • an object a1 which is an arbitrary copy of a made by the implementation
  • an object b meeting completion handler requirements
  • an object b1 which is an arbitrary copy of b made by the implementation

if any of the following conditions are true:

  • s.post(a) happens-before s.post(b)
  • ...

then asio_handler_invoke(a1, &a1) happens-before asio_handler_invoke(b1, &b1).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...