Search code examples
rustasync-awaitconcurrencyrust-tokio

Is tokio multithreaded?


I know tokio allows to write concurrent code. But I'm not sure if it runs in parallel. My computer has eight cores. So ideally I would run no more than eight threads. If I needed more concurrency I would run coroutines on top of those threads (using tokio).

Unless of course, tokio was already multithreaded. In that case, creating those eight threads in the beginning would be counterproductive. So what I am trying to ask is, is tokio multithreaded by default, or is that something I should implement myself?


Solution

  • Yes. Tokio is multi-threaded. By default, it creates as many worker threads as there are cores. You can customize how many worker threads the runtime creates via the tokio::main macro. Example:

    #[tokio::main(flavor = "multi_thread", worker_threads = 10)]
    async fn main() {
        // your code here
    }