What's the difference between asio::io_context and asio::thread_pool?
Asked Answered
W

1

8

Whats the difference between an asio::thread_pool and an asio::io_context whose run() function is called from multiple threads? Can I replace my boost::thread_group of threads that call io_context::run() with an asio::thread_pool? Or do I need somewhere an io_context?

Update

When I use asio::thread_pool, do I still need an io_context to use sockets, timers, etc? Both thread_pool and io_context are an asio::execution_context. However, the docs say on io_context that it "Provides core I/O functionality". Do I lose these if I only use an asio::thread_pool without an io_context?

Waisted answered 18/5, 2020 at 7:29 Comment(0)
A
8

A threadpool implicit runs all the tasks posted on it (until it's stopped).

An io_service doesn't assume anything about the threads that will run it: you need to make sure you do that, and you're free to decide whether you run it on multiple threads, one thread, or even a mix (like one thread at at time, but from multiple threads?).

Further notes:

Amaral answered 18/5, 2020 at 19:11 Comment(4)
Excellent points and links, thanks! I'll consider these. One thing is still unclear to me (I've updated the question): Do I need an io_service to use sockets and timers? Or does the thread_pool provide the same functionalities?Waisted
@ValarMorghulis Both io_context and thread_pool are perfectly capable execution_context instances. In fact, for specific services using only one execution context could be more efficient than multiple. See https://mcmap.net/q/1150193/-boost-asio-multiple-threads-and-multiple-io_service or #6055996Amaral
You can control how threads are created and then attached to a thread_pool. Initialize an empty pool by calling the thread_pool constructor with integer argument and passing 0. Then create your threads and call the thread_pool.attach() method. Simplest example: auto* t = new std::thread([](){pool.attach()});Offensive
@Offensive Do not use new there (consider maybe detach() instead). Also, that's not full control: It's merely the option to grow, never shrink. That could be very important if your threads need thread-local initializations (like mysql_thread_init, or your own singleton instances)Amaral

© 2022 - 2024 — McMap. All rights reserved.