1. Basic concepts of blocking IO and non-blocking IO
1.1 Blocking IO
- Definition: After the process initiates an IO operation, if the data is unavailable, the process will be suspended (blocked) until the data is ready.
- Features: Simple and intuitive, but will cause the process to pause other tasks
1.2 Non-blocking IO
- Definition: After the process initiates an IO operation, if the data is not available, the error code (EAGAIN/EWOULDBLOCK) will be returned immediately and the process will not be blocked.
- Features: The process can continue to perform other tasks, but needs to poll to check whether the data is ready.
2. Set IO blocking/non-blocking mode
// Set non-blocking when onint fd = open("/dev/device", O_RDWR | O_NONBLOCK); // Modify the opened file to be non-blockingint flags = fcntl(fd, F_GETFL, 0); fcntl(fd, F_SETFL, flags | O_NONBLOCK); // Modify to blocking modefcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
3. Comparison of blocking IO and non-blocking IO
Blocking IO:
- Advantages: The programming model is simple, no additional state check is required, no CPU resources are used to wait for data
- Disadvantages: The thread is blocked and cannot handle other tasks, and multi-threading needs to handle multi-IO operations.
Non-blocking IO:
- Advantages: Single thread can handle multiple IO operations, and will not be blocked by IO operations, and can handle other tasks at the same time.
- Disadvantages: It requires continuous polling, consumes CPU resources, complex code logic, and difficult to set the polling frequency
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.