Timeout¶
Category: Async · Status: stub · Lessons: chapter 06, Async (planned)
One line: Giving up on an operation after a time limit — which, in concurrent code, means cancelling or abandoning whatever was still running on its behalf.
Also called: deadline.
How it connects¶
flowchart LR
n_cancellation["Cancellation"]
n_deadlock["Deadlock"]
n_timeout["Timeout"]
n_timeout -->|prevents| n_deadlock
n_timeout -->|uses| n_cancellation
classDef center stroke-width:3px
class n_timeout center
classDef outside stroke-dasharray: 4 3
class n_cancellation,n_deadlock outside
- Is built on: Cancellation
- Helps prevent: Deadlock
- See also: Cancellation, Partial failure, Select, Timers and tickers
In each language¶
| Rust | Receiver::recv_timeout ↗ on a channel; tokio's time::timeout ↗ requires a future to complete before a duration has elapsed |
| Go | context.WithTimeout ↗ for a whole call tree; time.After ↗ as one case of a select |
| C | pthread_cond_timedwait ↗, which takes an absolute time |
| C++ | std::future::wait_for ↗, which returns future_status::timeout |
| Java | Future.get ↗ with a timeout throws TimeoutException; CompletableFuture.orTimeout ↗ |
| Python | asyncio.timeout ↗ cancels the task and turns the CancelledError into a TimeoutError; asyncio.wait_for ↗ |
| C# | CancellationTokenSource.CancelAfter ↗, and Task.WaitAsync ↗ with a TimeSpan |
| JavaScript | AbortSignal.timeout() ↗ returns a signal that aborts with a TimeoutError |
| Kotlin | withTimeout ↗ cancels its block with a TimeoutCancellationException; withTimeoutOrNull is the variant the guide ↗ uses |
| Erlang and Elixir | an after clause on receive, in Erlang ↗ and Elixir ↗ |
| Haskell | System.Timeout.timeout ↗ |
Where to read more¶
- In a sibling library: Go: A timeout is a channel ↗
- In a sibling library: Go: A deadline is a cancel with a clock ↗
- In the books: Parallel and Concurrent Programming in Haskell, Simon Marlow — ch. 9, 'Cancellation and Timeouts'
- In the books: Concurrency in Go, Katherine Cox-Buday — ch. 5, 'Concurrency at Scale' → 'Timeouts and Cancellation'
- In the books: C++ Concurrency in Action, Anthony Williams — ch. 4, 'Synchronizing concurrent operations' → 'Waiting with a time limit'
- In the books: Concurrency in C# Cookbook, Stephen Cleary — ch. 6, 'System.Reactive Basics' → 'Timeouts'
- In the books: Python Concurrency with asyncio, Matthew Fowler — ch. 2, 'asyncio basics' → 'Canceling tasks and setting timeouts'
- In the books: Combine: Asynchronous Programming with Swift, Shai Mishali, Florent Pillet, Marin Todorov, Scott Gardner — ch. 6, 'Time Manipulation Operators' → 'Timing out'