5

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
George
  • 3,521
  • 4
  • 30
  • 75

1 Answers1

8

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.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • May I ask, if you know, why does the `tokio_current_thread` crate exist if this runtime build is already a thing ? Does it provide advantages for single-threaded scenarios ? – George Oct 16 '18 at 20:01
  • 1
    If you use the current thread executor, I think you have fewer restrictions on your futures, since they don't need to be `Send`. With the threaded executor, all futures need to be `Send` even when you only use a single thread. (I may be mixing up the terminology, but it's something along these lines.) – Sven Marnach Oct 16 '18 at 20:04