What's the Difference Between Blocking vs Non-Blocking and Sync vs Async?
Overview
During application development, we often confront terms like "Blocking," "Non-blocking," "Synchronous," and "Asynchronous." It's a common misconception to view these as synonymous. In reality, they represent distinct, albeit intertwined, concepts.
One frequent point of confusion is between "Blocking" and "Synchronous" and between "Non-blocking" and "Asynchronous."
In essence:
- "Synchronous" and "Asynchronous" processes involve at least two subjects. When their task durations align, it's "Synchronous"; if not, it's "Asynchronous."
- "Blocking" and "Non-blocking" describe how systems handle tasks. These terminologies are primarily applied to I/O operations.
Let's delve into these concepts in more detail.
Concept
1. Understanding Blocking vs. Non-Blocking
The crux of this distinction lies in how a system responds when waiting for another process.
- Blocking: The system waits for another process to complete before resuming its task. Think of a Java JDBC querying a database—it waits for a response.
- Non-Blocking: The system continues its operation, irrespective of other processes. It doesn't wait.
2. Deciphering Synchronous vs. Asynchronous
When considering multiple subjects executing tasks:
- Synchronous: The tasks align, either starting or ending simultaneously.
- Asynchronous: Task start/end times are independent of each other.
3. Blocking/Non-blocking vs. Sync/Async
When an I/O function is invoked:
- Blocking: Waits for the process to complete before returning.
- Non-Blocking: Returns immediately, regardless of whether the task has finished.
In terms of who oversees task completion for the I/O function:
- Synchronous: Managed by the application.
- Asynchronous: Overseen by the kernel.
Based on the combinations of Blocking/Non-Blocking and Synchronous/Asynchronous, the four resulting quadrants are shown in the diagram below:
Examples of Their Combinations
- Synchronous Blocking I/O
This is the most straightforward method of I/O. When you make a call, the program waits for the operation to complete before moving on.
代码语言:javascript复制#include <iostream>
#include <fstream>
int main() {
std::ifstream file("example.txt");
std::string content;
// This line blocks until the entire file is read
std::getline(file, content, '