Blocking the event loop¶
Category: Async · Status: stub · Lessons: chapter 06, Async (planned)
One line: A task that computes for a long time, or makes a blocking call, on the runtime's thread stops every other task on that thread until it is done.
Also called: blocking in async code.
How it connects¶
flowchart LR
n_blocking_the_event_loop["Blocking the event loop"]
n_cooperative_scheduling["Cooperative scheduling"]
n_starvation["Starvation"]
n_blocking_the_event_loop -->|can cause| n_starvation
n_cooperative_scheduling -->|can cause| n_blocking_the_event_loop
classDef center stroke-width:3px
class n_blocking_the_event_loop center
classDef outside stroke-dasharray: 4 3
class n_cooperative_scheduling,n_starvation outside
- Can lead to: Starvation
- Can be caused by: Cooperative scheduling
- See also: Event loop, Function coloring, UI thread
In each language¶
| Rust | tokio's spawn_blocking ↗ runs blocking work on a thread dedicated to it, because a future that does not yield keeps the executor from driving other futures |
| Go | there is no event loop to block, and since Go 1.14 ↗ goroutines are asynchronously preemptible, so even a loop without function calls cannot hold up the scheduler |
| Java | a virtual thread that blocks releases its platform thread; JEP 491 ↗ (JDK 24) made that happen inside synchronized too |
| Python | blocking (CPU-bound) code should not be called directly; loop.run_in_executor or asyncio.to_thread ↗ moves it off the loop (asyncio guide ↗) |
| JavaScript | Node runs callbacks on the Event Loop and expensive tasks on a Worker Pool; a thread blocked on behalf of one client cannot serve any other (guide ↗) |
Where to read more¶
- In the books: Parallel Programming and Concurrency with C# 10 and .NET 6, Alvin Ashcraft — ch. 4, 'User Interface Responsiveness and Threading'
- In the books: Python Concurrency with asyncio, Matthew Fowler — ch. 6, 'Handling CPU-bound work'
- In the books: asyncio Recipes, Mohamed Mustapha Tahrioui — ch. 10, 'Preventing Common Asyncio Mistakes'
- In the books: High Performance JavaScript, Nicholas C. Zakas — ch. 6, 'Responsive Interfaces'