如何在单线程编程模型异步编程的工作? [英] How does Asynchronous programming work in a single threaded programming model?

查看:163
本文介绍了如何在单线程编程模型异步编程的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在经历的的node.js 的细节,才知道,它支持异步编程,虽然本质上它提供了一个单线程模式。

I was going through the details of node.jsand came to know that, It supports asynchronous programming though essentially it provides a single threaded model.

如何异步编程在这种情况下如何处理?是像运行时本身创建和管理线程,但程序员不能明确创建线程?这将是巨大的,如果有人可以点我的一些资源,了解这一点。

How is asynchronous programming handled in such cases? Is it like runtime itself creates and manages threads, but the programmer cannot create threads explicitly? It would be great if someone could point me to some resources to learn about this.

推荐答案

我现在说出来:异步编程并不一定意味着多线程

JavaScript是单线程运行时 - 你根本无法在JS来创建新的线程,因为语言/运行时不支持它

Javascript is a single-threaded runtime - you simply aren't able to create new threads in JS because the language/runtime doesn't support it.

弗兰克说,它正确地(虽然钝)英文:有一个主事件循环,当事情进入你的应用程序处理。所以,处理这个HTTP请求将被添加到事件队列中,然后由事件循环处理,在适当的时候。

Frank says it correctly (although obtusely) In English: there's a main event loop that handles when things come into your app. So, "handle this HTTP request" will get added to the event queue, then handled by the event loop when appropriate.

当你调用一个异步操作(MySQL数据库查询,例如),Node.js的发出哎,执行这个查询到MySQL。由于此查询需要一定的时间(毫秒),node.js的执行使用MySQL异步库查询 - 又回到了事件循环和做的别的的有等待的mysql要回美国。像处理的HTTP请求。​​

When you call an async operation (a mysql db query, for example), node.js sends "hey, execute this query" to mysql. Since this query will take some time (milliseconds), node.js performs the query using the MySQL async library - getting back to the event loop and doing something else there while waiting for mysql to get back to us. Like handling that HTTP request.

修改:相比之下,node.js中的可能的只是等待MySQL来取回它周围的(什么都不做)。这就是所谓的同步呼叫。想象一下,一个餐厅,在这里你的服务员提交您为了厨师,然后坐下来,旋转因子他/她的拇指,而厨师厨师。在一间餐厅,就像在Node.js的程序,这样的行为是愚蠢的 - 你谁是​​饿了,需要送达其他客户。因此,要尽可能同步,以确保一个侍者(或Node.js的过程)被作为许多人,因为他们可以。

Edit: By contrast, node.js could simply wait around (doing nothing) for mysql to get back to it. This is called a synchronous call. Imagine a restaurant, where your waiter submits your order to the cook, then sits down and twiddles his/her thumbs while the chef cooks. In a restaurant, like in a node.js program, such behavior is foolish - you have other customers who are hungry and need to be served. Thus you want to be as asynchronous as possible to make sure one waiter (or node.js process) is serving as many people as they can.

修改完成

Node.js的MySQL的使用C库进行通信,所以在技术上这些C库可以产卵关闭线程,但Javascript中你不能做任何事情的线程

Node.js communicates with mysql using C libraries, so technically those C libraries could spawn off threads, but inside Javascript you can't do anything with threads.

这篇关于如何在单线程编程模型异步编程的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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