Tokio context switching for spawn vs spawn_blocking?

Await points don't do "explicit context switching." Even when you use tokio's single-threaded scheduler, it may choose any future to run if more than one is ready/pollable. See Alice's post for details.

If you want JS-like tasks that run on a single thread and never run concurrently, use tokio's LocalSet.

Otherwise, whatever context-switching the kernel does underneath is not something you'll notice - for instance, the kernel may time-multiplex your Rust application threads (including those in the tokio worker pool) with others if there are not enough core on the machines. I get the sense though that that's not what you're asking, based on your comment that (execution) is "unpredictable as with regular multi-threaded code," you're probably interested in the consequences of the underlying schedulers' behavior on your code.

1 Like