异步调用和非阻塞调用之间的区别是什么?在阻塞和同步调用之间(请提供示例)?
当前回答
在许多情况下,它们是同一事物的不同名称,但在某些情况下,它们是完全不同的。这要看情况。在整个软件行业中,术语的应用并不是完全一致的。
例如,在经典的套接字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.
其他回答
阻塞调用:控制只在调用完成时返回。
非阻塞调用:控制立即返回。之后的操作系统以某种方式通知进程调用已经完成。
同步程序:使用阻塞调用的程序。为了在调用期间不被冻结,它必须有2个或更多的线程(这就是为什么它被称为同步-线程同步运行)。
异步程序:使用非阻塞调用的程序。它可以只有一个线程,但仍然保持交互。
把这个问题放在java 7中的NIO和NIO.2上下文中,异步IO比非阻塞先进了一步。 使用java NIO非阻塞调用,可以通过调用abstractselectablecchannel . configureblocking (false)来设置所有通道(SocketChannel、ServerSocketChannel、FileChannel等)。 然而,在这些IO调用返回之后,您可能仍然需要控制检查,例如是否以及何时再次读/写等等。 例如,
while (!isDataEnough()) {
socketchannel.read(inputBuffer);
// do something else and then read again
}
使用java 7中的异步api,可以以更通用的方式创建这些控件。 两种方法之一是使用CompletionHandler。注意,两个读调用都是非阻塞的。
asyncsocket.read(inputBuffer, 60, TimeUnit.SECONDS /* 60 secs for timeout */,
new CompletionHandler<Integer, Object>() {
public void completed(Integer result, Object attachment) {...}
public void failed(Throwable e, Object attachment) {...}
}
}
它们只在拼写上有所不同。它们所指的内容没有区别。从技术上讲,你可以说它们的重点不同。非阻塞指的是控制流(它不阻塞)。异步是指当事件\数据被处理时(不是同步的)。
synchronous | asynchonous | |
---|---|---|
block | Block I/O must be a synchronus I/O, becuase it has to be executed in order. Synchronous I/O might not be block I/O | Not exist |
non-block | Non-block and Synchronous I/O at the same time is polling/multi-plexing.. | Non-block and Asynchronous I/O at the same time is parallel execution, such as signal trigger… |
block/non-block描述了初始化实体本身的行为,它意味着实体在等待I/O完成期间所做的事情 同步/异步描述了I/O初始化实体和I/O执行器(例如操作系统)之间的行为,它意味着这两个实体是否可以并行执行
简单地说,
function sum(a,b){
return a+b;
}
为非阻塞。而异步则用于执行阻塞任务,然后返回阻塞任务的响应