-
I've been going through Tokio's mini-redis tutorial where it says:
So it sounds like Tokio itself decides when to spawn new threads / move tasks to those threads. If that's the case - how is that determined? Context: for one of the apps I'm building I'm thinking whether to keep a task on the main async runtime or whether to spin up a new thread and start another async runtime there. The latter feels structurally cleaner, but if under the hood Tokio starts threads itself then I'm doing double work. How should I think about it? Any links I can read to educate myself super welcome. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Tokio has two kinds of threads:
To answer your question, we need to consider these separately. Worker threads. The number of worker threads never changes. Each worker thread can execute an unbounded number of asynchronous tasks concurrently. When you start the runtime, it looks up how many CPU cores you have and spawns that many worker threads. You can configure the amount of worker threads on the runtime builder, or as an option to Blocking threads. Tokio will not spawn any blocking threads until they are needed due to calls to Generally you do not gain any advantage from increasing the number of worker threads beyond the number of CPU cores, as that is the limit of parallelism on your machine. The one exception is if one of the async tasks is blocking the thread, but here the fix is to not block the thread, or to do it outside the worker thread (read the link for details). Spawning more worker threads to combat blocking is counterproductive. |
Beta Was this translation helpful? Give feedback.
Tokio has two kinds of threads:
tokio::spawn
tokio::task::spawn_blocking
.To answer your question, we need to consider these separately.
Worker threads. The number of worker threads never changes. Each worker thread can execute an unbounded number of asynchronous tasks concurrently. When you start the runtime, it looks up how many CPU cores you have and spawns that many worker threads. You can configure the amount of worker threads on the runtime builder, or as an option to
#[tokio::main]
. Asynchronous tasks may be moved from one worker thread to another at any.await
to more evenly d…