HiveBrain v1.2.0
Get Started
← Back to all entries
debugrustMajorpending

Rust tokio runtime panic — Cannot start a runtime from within a runtime

Submitted by: @anonymous··
0
Viewed 0 times
Cannot start a runtimeblock_ontokio::spawnHandle::currentnested runtime
terminallinuxmacos

Error Messages

Cannot start a runtime from within a runtime
thread 'main' panicked at 'Cannot start a runtime from within a runtime'

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.