跳至主要內容

理解同步、异步、阻塞和非阻塞

post杂谈大约 3 分钟

理解同步、异步、阻塞和非阻塞

关于同步、异步、阻塞和非阻塞这个概念性问题,这可能是非常容易混淆的概念之一,特别是那些刚开始解除网络编程的人来说。本篇文章争取来说清楚这个问题,如果有错误之处,恳请批评指正。

写在前面

首先大家心中需要有以下的清晰认知:

  • 阻塞操作不等于同步(blocking operation does NOT equal to synchronous)
  • 非阻塞操作不等于异步(non-blocking operation does NOT equal to asynchronous)

事实上,同步异步于阻塞和非阻塞没有什么直接的关联关系。

同步和异步

同步和异步关注的是 通信机制 (communication mechanism)

  • 同步是指在发出一个function调用时,在没有得到结果之前,该调用就不返回。但是一旦调用返回,就得到调用结果了。这个结果可能是一个正确的期望结果,也可能是因为异常原因(比如超时)导致的失败结果。换句话说,就是由调用者主动等待这个调用的结果。

Synchronous is, when we started a function call, the call will not return anything until it gets the result, the function needs to finish everything before it can give anything to us.

  • 异步调用在发出之后,本次调用过程就直接返回了,并没有同时没有返回结果。换句话说,当一个异步过程调用发出后,调用者不会立刻得到结果。而是在调用发出后,被调用者通过状态变化、事件通知等机制来通知调用者,或通过回调函数处理这个调用。

Asynchronous does not need to wait for the function completes its operation, once we call it, it returns immediately without any result, the function uses callback function (or other notification method) to "notify" us to get the value after it completes execution.

阻塞和非阻塞

阻塞和非阻塞关注的是 程序在等待调用结果(消息、返回值)时的状态.

Unlike synchronous/asynchronous, blocking/non-blocking focuses on the status of the program while waiting for the result from the function call.

  • 阻塞调用是指调用结果返回之前,当前线程会被挂起。调用线程只有在得到结果之后才会返回

A blocking operation hangs up current thread before it gets the result, in other words, a blocking operation will let the current thread wait for the result returns, even if the target function will use a callback function to notify client side to fetch the result, the thread on the client side will still be blocked until it gets the returned result.

  • 非阻塞是指在不能立刻得到结果之前,该调用不会阻塞当前线程。

the non-blocking operation will not hang up the current thread if no result returned immediately.

对unix操作系统来讲:

  • 阻塞式I/O(默认),非阻塞式I/O(nonblock),I/O复用(select/poll/epoll)都属于同步I/O,因为它们在操作系统将数据由内核缓冲区复制到用户空间缓冲区时都是阻塞的(不能干别的事)。
  • 只有异步I/O模型(AIO)是符合异步I/O操作的含义的,即在数据准备完成以后,由内核空间拷贝回用户缓冲区后再通知通知用户进程,而用户进程在等待通知的这段时间里可以干别的事。

前几天看到了下面的代码片段,我觉的写的挺好的,复制一下:

http://wenchao.ren/img/2020/11/20190329000237.png
http://wenchao.ren/img/2020/11/20190329000237.png

接下来我会写一篇介绍unix IO模型的文章,在这篇文章中,我会具体谈谈不同的IO模型。

参考资料


版权申明

本站点所有内容,版权均归https://wenchao.renopen in new window所有,除非明确授权,否则禁止一切形式的转载协议

打赏

微信 支付宝

上次编辑于:
打赏
给作者赏一杯咖啡吧
您的支持将是我继续更新下去的动力
微信微信
支付宝支付宝