Future and Callback Contracts · 14 min · free with an account

Lock Scope Across await

Lesson preview · about 30%

Keep synchronous critical sections short and make suspension while holding a guard an explicit design decision.

Core idea

Waiting for a lock, holding a lock during suspension and doing CPU work are separate concerns.

Start with the idea

A standard mutex can be a reasonable choice for a short critical section that does not cross await. Acquiring a contended synchronous mutex can block the executor worker. Holding its guard while a future suspends is a separate problem: it keeps the lock unavailable and can violate a Send bound or participate in a deadlock.

The example updates a counter inside a lexical scope, drops the guard and only then awaits. A compile-time Send check confirms this particular future does not retain the standard MutexGuard across suspension. It does not prove absence of every deadlock or that every acquisition is cheap.

An async mutex can yield while waiting for its lock, but it does not make arbitrary guarded work nonblocking.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 754 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Rust Interview Prep