How to use boost::asio::io_service::run_one()

2019-07-23 11:44发布

问题:

I was reading up on boost::asio::io_service::run_one() and am confused by what it means by the function block. What has been blocked and where is the handler defined?

回答1:

I was reading up on boost::asio::io_service::run_one() and am confused by what it means by the function block. What has been blocked

Blocked means run_one() blocks until it completes one handler.

and where is the handler defined?

It isn't. Logically it's described in the documentation. A handler is whatever action is pending in the service. So, if you do:

 void foo() { /*.... */ }
 void bar() { /*.... */ }

 io_service svc;
 svc.post(foo);
 svc.post(bar);

Now the first time you call

 svc.run_one();

blocks until foo is completed. The second time

 svc.run_one();

will block until bar is completed. After that, run_one() will NOT block and just return 0. If you make the service stay around, e.g.:

 io_service::work keep_around(svc);
 svc.run_one();

would block until some other action was posted.