Blocking and non-blocking calls¶
Category: Foundations · Status: stub · Lessons: chapter 06, Async (planned)
One line: A blocking call does not return until its work is done, holding the caller's thread the whole time; a non-blocking call returns at once and reports that the work is not ready yet or will finish later.
Also called: synchronous and asynchronous calls, blocking I/O, non-blocking I/O.
How it connects¶
- See also: Asynchrony, I/O multiplexing, I/O-bound and CPU-bound work, Polling
In each language¶
| Rust | TcpStream::set_nonblocking ↗ makes a read that would wait return an io::ErrorKind::WouldBlock error instead |
| Go | A send or receive on an unbuffered channel ↗ blocks until the other side is ready |
| C | With O_NONBLOCK set, read ↗ fails with EAGAIN instead of waiting |
| Java | SelectableChannel.configureBlocking(false) ↗ puts an NIO channel in non-blocking mode |
| Python | socket.setblocking(False) ↗; in asyncio, asyncio.to_thread ↗ runs a blocking function that would otherwise block the event loop |
| C# | Asynchronous file I/O ↗ methods such as ReadAsync do the work without blocking the main thread |
| JavaScript | Atomics.wait ↗ blocks, and so cannot be used in the main thread |
| The operating system | The O_NONBLOCK flag of open(2) ↗; readiness is then waited for with poll or epoll |
Where to read more¶
- In the books: Java Concurrency in Practice, Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, Doug Lea — ch. 15, 'Atomic Variables and Nonblocking Synchronization'
- In the books: Grokking Concurrency, Kirill Bobrov — ch. 10, 'Nonblocking I/O'
- In the books: Rust Atomics and Locks, Mara Bos — ch. 5, 'Building Our Own Channels' → 'Blocking'
- In the books: Parallel and Concurrent Programming in Haskell, Simon Marlow — ch. 10, 'Software Transactional Memory' → 'Blocking'
- In the books: Concurrency in .NET, Riccardo Terrell — ch. 13, 'Recipes and design patterns for successful concurrent programming' → 'Non-blocking synchronous message-passing model'
- In the books: Python Concurrency with asyncio, Matthew Fowler — ch. 3, 'A first asyncio application' → 'Working with non-blocking sockets'
- Notes: non-blocking paradigms - general - nonblocking ↗
- Notes: blocked synchronously - general ↗
- Notes: Synchronous blocking vs nonblocking model ↗
- Notes: Asynchronous blocking vs nonblocking model ↗
- Notes: Blocking vs. non-blocking code - rust ↗
- Notes: blocking - thread - general ↗
- Reference: Wikipedia: Asynchronous I/O ↗