异步调用是否总是创建/调用新线程? [英] Does an asynchronous call always create/call a new thread?

查看:28
本文介绍了异步调用是否总是创建/调用新线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

异步调用是否总是创建一个新线程?

Does asynchronous call always create a new thread?

示例:

如果 JavaScript 是单线程的,那么它如何进行异步回发?在得到回调之前它实际上是阻塞的吗?如果是这样,这真的是异步调用吗?

If JavaScript is single threaded then how can it do an async postback? Is it actually blocking until it gets a callback? If so, is this really an async call?

推荐答案

这是一个有趣的问题.

异步编程是一种主要是单线程的编程范式,即跟随一个线程连续执行".

Asynchronous programming is a paradigm of programming that is principally single threaded, i.e. "following one thread of continuous execution".

您指的是 javascript,所以让我们在 Web 浏览器的环境中讨论该语言.Web 浏览器在每个窗口中运行一个 javascript 执行线程,它处理事件(例如 onclick="someFunction()")和网络连接(例如 xmlhttprequest 调用).

You refer to javascript, so lets discuss that language, in the environment of a web browser. A web browser runs a single thread of javascript execution in each window, it handles events (such as onclick="someFunction()") and network connections (such as xmlhttprequest calls).

<script>
function performRequest() {
  xmlhttp.open("GET", "someurl", true);
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4) {
      alert(xmlhttp.responseText);
    }
  }
  xmlhttp.send(sometext);
}
</script>
<span onclick="performRequest()">perform request</span>

(这是一个非工作示例,仅用于演示概念).

(This is a nonworking example, for demonstration of concepts only).

为了以异步方式执行所有操作,控制线程具有所谓的主循环".主循环看起来像这样:

In order to do everything in an asynchronous manner, the controlling thread has what is known as a 'main loop'. A main loop looks kind of like this:

while (true) {
    event = nextEvent(all_event_sources);
    handler = findEventHandler(event);
    handler(event);
}

需要注意的是,这不是一个忙循环".这有点像一个睡眠线程,等待活动发生.活动可以是来自用户的输入(鼠标移动、按钮点击、打字),也可以是网络活动(来自服务器的响应).

It is important to note that this is not a 'busy loop'. This is kind of like a sleeping thread, waiting for activity to occur. Activity could be input from the user (Mouse Movement, a Button Click, Typing), or it could be network activity (The response from the server).

所以在上面的例子中,

  1. 当用户点击 span 时,会生成一个 ButtonClicked 事件,findEventHandler() 会在 span 标签上找到 onclick 事件,然后该处理程序将随事件一起被调用.
  2. 创建 xmlhttp 请求后,它会被添加到事件源的 all_event_sources 列表中.
  3. 在 performRequest() 函数返回后,主循环在 nextEvent() 步骤等待响应.在这一点上,没有什么阻止"进一步的事件被处理.
  4. 数据从远程服务器返回,nextEvent() 返回网络事件,发现事件处理程序是 onreadystatechange() 方法,该方法被调用,并且 alert() 对话框启动.

值得注意的是,alert() 是一个阻塞对话框.当该对话框启动时,无法处理其他事件.网页的 javascript 模型的一个古怪之处在于,我们有一个现成的方法可以阻止在该页面的上下文中进一步执行.

It is worth noting that alert() is a blocking dialog. While that dialog is up, no further events can be processed. It's an eccentricity of the javascript model of web pages that we have a readily available method that will block further execution within the context of that page.

这篇关于异步调用是否总是创建/调用新线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆