异步调用和非阻塞调用之间的区别是什么?在阻塞和同步调用之间(请提供示例)?


当前回答

同步意味着按顺序在另一个结果之后启动一个。

异步意味着一起开始,结果上不保证顺序

阻塞是指某些东西导致执行下一步的阻碍。

无阻塞是指不等待任何东西就继续运行,克服障碍。

我敲门,等着他们开门。(我在这里无所事事)

我敲门,如果他们马上开门,我就和他们打招呼,然后走进去等等。如果门没有立刻打开,我就去下一户人家敲门。(我正在做某事,没有闲着)

只有在下雨的时候我才会出去。(依赖关系存在)

我要出去。可能会下雨。(独立事件,发生时间无关紧要)

同步或异步,两者都可以是阻塞或非阻塞的,反之亦然

其他回答

非阻塞调用立即返回任何可用的数据:请求的全部字节数、更少的字节数或根本没有。

异步调用请求的传输将以其整体(全部)执行,但将在未来某个时间完成。

阻塞调用:控制只在调用完成时返回。

非阻塞调用:控制立即返回。之后的操作系统以某种方式通知进程调用已经完成。


同步程序:使用阻塞调用的程序。为了在调用期间不被冻结,它必须有2个或更多的线程(这就是为什么它被称为同步-线程同步运行)。

异步程序:使用非阻塞调用的程序。它可以只有一个线程,但仍然保持交互。

正如你可能从众多不同的(通常是相互排斥的)答案中看到的,这取决于你问谁。在某些领域,这两个术语是同义词。或者它们可能分别指两个相似的概念:

One interpretation is that the call will do something in the background essentially unsupervised in order to allow the program to not be held up by a lengthy process that it does not need to control. Playing audio might be an example - a program could call a function to play (say) an mp3, and from that point on could continue on to other things while leaving it to the OS to manage the process of rendering the audio on the sound hardware. The alternative interpretation is that the call will do something that the program will need to monitor, but will allow most of the process to occur in the background only notifying the program at critical points in the process. For example, asynchronous file IO might be an example - the program supplies a buffer to the operating system to write to file, and the OS only notifies the program when the operation is complete or an error occurs.

在任何一种情况下,目的是允许程序不被阻塞,等待一个缓慢的进程完成-程序如何响应是唯一真正的区别。不同的程序员、不同的语言、不同的平台都不一样。或者这些术语可能指的是完全不同的概念(例如在线程编程中使用同步/异步)。

抱歉,但我不相信有一个唯一的正确答案是全面正确的。

简单地说,

function sum(a,b){
return a+b;
}

为非阻塞。而异步则用于执行阻塞任务,然后返回阻塞任务的响应

在许多情况下,它们是同一事物的不同名称,但在某些情况下,它们是完全不同的。这要看情况。在整个软件行业中,术语的应用并不是完全一致的。

例如,在经典的套接字API中,非阻塞套接字会立即返回一个特殊的“将阻塞”错误消息,而阻塞套接字则会阻塞。您必须使用单独的函数,如选择或轮询,以确定何时是重试的最佳时间。

但是异步套接字(Windows套接字支持)或。net中使用的异步IO模式更方便。您调用一个方法来启动一个操作,当操作完成时,框架会回调您。即使在这里,也有基本的区别。异步Win32套接字通过传递Window消息将结果“封送”到特定的GUI线程上,而. net异步IO是自由线程的(你不知道你的回调将被调用在哪个线程上)。

所以它们的意思并不总是一样的。要提取套接字示例,我们可以这样说:

Blocking and synchronous mean the same thing: you call the API, it hangs up the thread until it has some kind of answer and returns it to you. Non-blocking means that if an answer can't be returned rapidly, the API returns immediately with an error and does nothing else. So there must be some related way to query whether the API is ready to be called (that is, to simulate a wait in an efficient way, to avoid manual polling in a tight loop). Asynchronous means that the API always returns immediately, having started a "background" effort to fulfil your request, so there must be some related way to obtain the result.