How do I limit the Tokio threadpool to a certain number of native threads?

6.6k views Asked by At

What's the correct way of limiting the Tokio (v 0.1.11) threadpool to n OS native threads, where n is an arbitrary number, preferably configurable at runtime?

As far as I can tell, it's possible to use Tokio in single threaded mode using using tokio_current_thread::block_on_all instead of tokio::run and tokio_current_thread::spawn instead of tokio::spawn.

I'd like a similar solution but for n >= 1.

1

There are 1 answers

2
Sven Marnach On BEST ANSWER

You can build a Tokio Runtime object using tokio::runtime::Builder. The builder offers a core_threads() method that can be used to configure the number of threads, e.g.

let mut rt = runtime::Builder::new()
    .core_threads(4)
    .build()
    .unwrap();

You can then use rt.spawn(some_future) to run a future on this runtime.