并发在Node.js中如何工作? [英] How does concurrency work in nodejs?

查看:81
本文介绍了并发在Node.js中如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解并发如何在像nodejs这样的单线程环境中工作.

I am trying to understand how concurrency works in a single-threaded environment like nodejs.

假设我有以下代码:

var fs = require('fs');

fs.readFile('file1', function one(err, data) {
  // some code...
});

fs.readFile('/file2', function two(err, data) {
  // some code...
});

现在每个fs.readFile调用都是异步的.因此,它们正在同时运行.但是,如果所有这些都是在单个线程中发生的,那么如何实现并发呢? function onefunction two是在相同或不同的线程上运行吗?

Now each fs.readFile call is async. So, they are running concurrently. But if all this is happening in a single thread, then how is the concurrency achieved? Are function one and function two running on the same or different thread?

基本上,node.js如何处理并发?

Basically, how does node.js handle concurrency?

推荐答案

就Node而言,只有一个线程.异步调用被放入事件队列,并且仅在下一个滴答中运行.

As far as Node is concerned, there is only one thread. Asynchronous calls are put into the event queue and only run on the next tick.

对于Node传递给C ++的代码,所有选择均不适用.那里可能有线程,也可能没有.但这并不会真正影响您.

For code that Node passes off to C++, all bets are off. There might or might not be threads there. But it doesn't really affect you.

对我来说,最有效的解释是到底什么是事件循环?"菲利普·罗伯茨(Philip Roberts)的作品,因为他展示的慢动作可视化工具使一切都变得十分清晰(无论如何对我来说都是如此).

The explanation that has been the most effective for me is "What the heck is the event loop anyway?" by Philip Roberts because the slow-motion visualization tool he shows makes everything pretty clear (to me, anyway).

您可以在线试用Philip的工具 Loupe .

You can experiment with Philip's tool Loupe online.

这篇关于并发在Node.js中如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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