Skip to main content

Posts

Showing posts with the label Tokio

Fixing the "future cannot be sent between threads safely" Error in Rust

  If you are writing async Rust using Tokio, you have likely encountered this compiler error chain: error: future cannot be sent between threads safely --> src/main.rs:15:5 | 15 | tokio::spawn(async move { | ^^^^^^^^^^^^ future created by async block is not `Send` | = help: within `impl Future<Output = ()>`, the trait `Send` is not implemented for `std::sync::MutexGuard<'_, Data>` = note: required because it's used within this `async` block This error usually occurs when you hold a standard library  std::sync::MutexGuard  across an  .await  point. The Root Cause: Async State Machines and  Send To understand why this breaks, you must understand how Rust compiles  async  blocks and how the Tokio runtime schedules tasks. The State Machine:  When you write an  async  block, the compiler transforms it into a state machine generated as an anonymous  struct . Any variable that must exist...