Skip to content
systemcoding.dev
Concurrency

Call Async Code From Synchronous Rust With a Tokio Runtime Handle and block_on

Bridge sync and async Rust with a Tokio Runtime and Handle::block_on, and avoid the nested-runtime panic from calling block_on inside a task.

7 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Rust, C++ and Linux logos.

Real programs mix worlds. A command-line tool is synchronous but needs one HTTP call through an async client. A library exposes a blocking API over an async core. A thread started by a C library has to call back into Rust code written with async fn. The bridge is the same in all three: a Tokio Runtime or its Handle, and block_on. It is easy to get right and easy to get wrong in a way that panics at run time with the message "Cannot start a runtime from within a runtime". This post shows the three shapes of the bridge, the panic and its fix, with Tokio 1.x on Rust 1.90.

Build a runtime and block on a future

A Runtime owns the worker threads and the I/O driver. Create one explicitly instead of using #[tokio::main], and call block_on on a future: it runs that future to completion on the calling thread and returns its output.

src/main.rsrust
use std::time::Duration;
use tokio::runtime::Runtime;

async fn fetch_answer() -> u32 {
    tokio::time::sleep(Duration::from_millis(10)).await;
    42
}

fn main() {
    let rt = Runtime::new().expect("failed to build runtime");
    let answer = rt.block_on(fetch_answer());
    println!("answer = {answer}");
}
Text
answer = 42

Runtime::new builds the multi-threaded runtime with every driver enabled. It needs the rt-multi-thread feature, and this program also needs time for the sleep, so use features = ["rt-multi-thread", "time"] or full. block_on drives the future on the current thread, while spawned tasks run on the worker threads. When rt is dropped at the end of main, the runtime shuts down.

#[tokio::main] is shorthand for exactly this: it builds a runtime and wraps your async fn main in block_on.

A handle for other threads

A Runtime value is not meant to be passed around; a Handle is. rt.handle().clone() gives a cheap, cloneable reference that lets any thread spawn tasks onto the runtime or block on a future there.

src/main.rsrust
use std::thread;
use tokio::runtime::Runtime;

async fn double(x: u32) -> u32 { x * 2 }

fn main() {
    let rt = Runtime::new().unwrap();
    let handle = rt.handle().clone();

    let worker = thread::spawn(move || {
        // A plain OS thread, outside the runtime:
        handle.block_on(double(21))
    });

    println!("thread result = {}", worker.join().unwrap());
}
Text
thread result = 42

Handle::block_on runs the future on the calling thread, using the runtime's I/O driver and timers. It does not use the runtime's worker threads for the top-level future, but anything it spawns runs on them. This is the right tool for a thread that does not belong to the runtime.

The panic: block_on inside a task

Calling block_on from code that is already running on a runtime thread panics, because a worker thread blocking on a future could never let that thread drive the runtime. The classic accident is a synchronous function called from async code, which internally calls block_on:

src/main.rsrust
use tokio::runtime::Handle;

fn sync_wrapper() -> u32 {
    Handle::current().block_on(async { 1 })   // panics inside a runtime
}

#[tokio::main]
async fn main() {
    println!("{}", sync_wrapper());
}
Text
thread 'main' panicked at src/main.rs:4:27:
Cannot start a runtime from within a runtime. This happens because a function (like `block_on`) attempted to block the current thread while the thread is being used to drive asynchronous tasks.

The panic message names the cause. The line and column in your build will differ. There are three ways out, in order of preference.

Fix 1: stay async

If the caller is async, make the wrapper async fn and .await the inner future. This removes the bridge entirely and is almost always the right answer. The accident usually comes from a library that offered only a blocking function.

Fix 2: spawn_blocking, then block_on inside it

A closure given to spawn_blocking runs on a thread owned by the runtime's blocking pool, where blocking is allowed. From there Handle::block_on works:

src/main.rsrust
use tokio::runtime::Handle;

fn sync_wrapper(h: Handle) -> u32 {
    h.block_on(async { 1 })
}

#[tokio::main]
async fn main() {
    let h = Handle::current();
    let n = tokio::task::spawn_blocking(move || sync_wrapper(h)).await.unwrap();
    println!("{n}");
}
Text
1

Use this when a synchronous API, perhaps a trait you do not control, must call async code, and the whole thing is itself called from async code. The earlier post on spawn_blocking covers its limits.

Fix 3: block_in_place

tokio::task::block_in_place(|| ...) tells the multi-threaded scheduler that the current worker is about to block, so it moves the worker's other tasks to a different thread first. Inside the closure block_on is allowed.

src/main.rsrust
use tokio::runtime::Handle;

#[tokio::main(flavor = "multi_thread", worker_threads = 2)]
async fn main() {
    let v = tokio::task::block_in_place(|| {
        Handle::current().block_on(async { 7 })
    });
    println!("{v}");
}
Text
7

block_in_place panics on the current_thread runtime, since there is no other thread to hand work to. It also requires no 'static closure, which is its advantage over spawn_blocking: the closure can borrow local data.

Building a blocking facade over an async library

To offer a synchronous API, keep the runtime inside the struct and make each method call block_on:

src/main.rsrust
use tokio::runtime::{Builder, Runtime};

struct Client { rt: Runtime }

impl Client {
    fn new() -> Self {
        let rt = Builder::new_current_thread().enable_all().build().unwrap();
        Client { rt }
    }
    fn get(&self, key: &str) -> String {
        self.rt.block_on(async { format!("value-of-{key}") })
    }
}

fn main() {
    let c = Client::new();
    println!("{}", c.get("a"));
}
Text
value-of-a

A current-thread runtime is enough for a facade because block_on drives the future itself. The reqwest crate's blocking module is built this way. Document that the methods must not be called from within an async context, because that is the panic described above, and consider detecting it with Handle::try_current().

Detecting the wrong context early

A library that offers a blocking facade can fail more kindly than a deep panic. Handle::try_current() returns Ok(handle) when the calling thread is inside a runtime and Err otherwise, so a facade can check first and return its own error message that names your function:

src/main.rsrust
use tokio::runtime::Handle;

fn check_context() -> &'static str {
    match Handle::try_current() {
        Ok(_) => "inside a runtime: do not call block_on here",
        Err(_) => "plain thread: block_on is allowed",
    }
}

fn main() {
    println!("{}", check_context());
}
Text
plain thread: block_on is allowed

In main without #[tokio::main] there is no runtime context, so the second branch runs. Call the same function from inside an async fn and the first branch would print. Failing with a descriptive message is friendlier to your users than the generic panic.

Which worker runs the future

It helps to know where code actually executes. With Runtime::block_on, the future you pass runs on the thread that called it, not on a worker. Tasks you tokio::spawn from inside it run on workers, so the outer future and the spawned tasks can run at the same time on different cores. On a current-thread runtime there are no workers at all, so spawned tasks make progress only while some thread is inside block_on, which is why a program that spawns and then returns from block_on early can drop work on the floor. If you need to wait for spawned work, await its JoinHandle before the block_on future finishes.

Dropping the Runtime waits for tasks to be cancelled, and it blocks the dropping thread while it does that. Runtime::shutdown_background and shutdown_timeout exist for the cases where waiting indefinitely is not acceptable, for example when a task is stuck in a blocking call.

Choosing between the bridges

Three situations call for different tools. A command-line program that is mostly synchronous and needs one or two async calls should build a runtime in main and use block_on at the edges, which keeps the sync code sync. A library that wants to offer both APIs should keep its core async and put the blocking facade behind a feature or a blocking module, so that async users never pay for a hidden runtime. A callback from a foreign thread, for example from a C library, should carry a cloned Handle captured at registration, and use handle.spawn for work that need not return a value, which is non-blocking, instead of block_on. In every case the hazard is the same: a hidden block_on inside code that an async caller might reach.

Also inDebugging
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.