Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can boost::asio::thread_pool be used instead of combining boost::asio::io_context with a boost::thread::thread_group?

Tags:

c++

boost-asio

I'm trying to clear up some confusion I have. I stumbled over boost::asio::thread_pool and I thought that one could use to somehow automatically combine boost::asio::io_context and boost::thread::thread_group like is often suggested (here or here). It appears that this asio-specific pool can be used to post tasks to but, on the other hand, some networking types like resolver need to be passed an object io_context as a constructor parameter which thread_pool isn't and doesn't derive from.

like image 968
screwnut Avatar asked Sep 18 '18 00:09

screwnut


2 Answers

Say you have a single io_context object, named ioc.

You can create several threads, and call ioc.run() in each one of them. This is a blocking operation that blocks on epoll/select/kqueue. Note that ioc is shareable, and by calling ioc.run() in several threads, they implicitly belong to a thread pool to be used by ioc. Let's call this pool io_threadpool.

Now create a separate pool of threads called compute, that do other things. Here is what is possible:

  • You can use ioc in threads from both pools (except for a few, like restart(), which require that ioc is not actively running).

  • You can make sync I/O calls from any thread.

  • You can invoke an async call like async_read( ..., handler) from any thread. However, the handler is only invoked in one of the io_threadpool threads.

  • You can dispatch tasks in either thread pool, but if the task is not going to do any I/O, I expect it to be more efficient to dispatch it in the compute pool, because the system doesn't have to wake up the epoll()/kqueue()/select() call on which it is blocked.

like image 199
Sriram Srinivasan Avatar answered Nov 11 '22 13:11

Sriram Srinivasan


You should post your io_context.run() into the thread_pool.

like image 23
user2709407 Avatar answered Nov 11 '22 12:11

user2709407