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

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

问题描述

我正在浏览 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 db 查询)时,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 使用 C 库与 mysql 通信,所以从技术上讲,这些 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天全站免登陆