debugrustMajorpending
Rust tokio runtime panic — Cannot start a runtime from within a runtime
Viewed 0 times
Cannot start a runtimeblock_ontokio::spawnHandle::currentnested runtime
terminallinuxmacos
Error Messages
Problem
Calling tokio::runtime::Runtime::new() or block_on() inside an existing async context panics with 'Cannot start a runtime from within a runtime'. Common when mixing sync and async code.
Solution
(1) Never create a new Runtime inside an async fn — use tokio::spawn instead. (2) If you must call async from sync code that's already in a runtime: use tokio::task::spawn_blocking to move to a blocking thread, then use a new Runtime there. (3) Use Handle::current() to get the current runtime handle and spawn tasks on it. (4) For library code: accept a runtime handle as parameter instead of creating one. (5) Use #[tokio::main] only at the entry point. (6) For tests: use #[tokio::test] instead of creating runtimes manually.
Why
Tokio is single-threaded per core by default. Creating a nested runtime would deadlock because the outer runtime's thread is blocked waiting for the inner one, but the inner one needs that thread.
Revisions (0)
No revisions yet.