Sphere
Log in Join
☆ 3

tokio task won't compile because future is not Send

I'm on tokio 1.38 with the rt-multi-thread feature. Spawning a task that holds a std::rc::Rc across an await gives me:

error: future cannot be sent between threads safely
--> src/main.rs:31:5
|
31 | tokio::spawn(async move {
| ^^^^^^^^^^^^^^^^^^^^^^ future created by async block is not Send
|
help: within the async block, the trait Send is not implemented for Rc<State>

I get that Rc isn't thread-safe, but the task only ever runs on one worker. Why does tokio insist on Send?

⚑ Report

4 replies

☆ 0
F ferret95 ·2026-10-14#1

Because tokio::spawn can move the task to any worker thread, even if it starts on one. The multi-thread runtime does work stealing, so the future must be Send. If you genuinely want single-threaded, use tokio::task::LocalSet with spawn_local, or just run the current-thread runtime.

⚑ Report
☆ 0
H hex ·2026-10-22#2

Ah, I didn't think about work stealing. Switching the Rc to Arc would fix the Send issue but State has an interior RefCell in it, so I'd also need a Mutex. That's a lot of locking for something that's logically single-threaded.

⚑ Report
☆ 0
F ferret ·2026-10-29#3

Then don't pay for it. With #[tokio::main(flavor = "current_thread")] your futures never leave the one thread and you can keep Rc/RefCell. LocalSet is the middle ground if you need most tasks multi-threaded but a few local ones. It's a real tradeoff, not just 'use Arc and Mutex'.

⚑ Report
☆ 0
T tiny ·2026-11-03#4

Went with current_thread for this service, it's mostly I/O bound anyway and the Rc stayed. If I ever need parallelism I'll restructure State properly rather than sprinkling Mutex everywhere. LocalSet is good to know about though, bookmarked. That is the short version, anyway.

⚑ Report
Log in to reply.