如何既JS非阻塞/异步但单线程? [英] How is JS both non-blocking / asynchronous but single-threaded?

查看:199
本文介绍了如何既JS非阻塞/异步但单线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有麻烦的JavaScript可视化如何既可以是单线程的,但在客户端上无阻塞。我总是想象像一条流水线:

I'm having trouble visualizing how Javascript can be both single-threaded but non-blocking on the client. I've always envisioned something like an assembly line:


  • 在你的code开始执行时,你有一个单一的组装线放在一起的不同部件的汽车。

  • At the start of your code execution, you've got a single assembly line putting together different parts to a car.

我们得到一个点,在20%的-to-完成,其中的发动机需要被添加,但发动机尚未组装还

We get to a point at 20%-to-completion where an engine needs to be added, but an engine hasn't been assembled yet.

而不是等待发动机进行组装,组装线被分成两个组装线 - ?两个线程,右

Instead of waiting for the engine to be assembled, the assembly line gets broken up into two assembly lines - two threads, right?

1号线将继续组装汽车的其他部分。

Line 1 continues to assemble the other parts of the car.

2号线开始装配引擎。

Line 2 starts to assemble the engine.

在第2行结束该发动机的组装,它会返回到1号线和添加发动机。

When Line 2 finishes the assembly of the engine, it goes back into Line 1 and the engine is added.

-to-完成,99%-to-完成等在这一点取决于发动机是如何快速组装线1可以在30%的

Line 1 could be at 30%-to-completion, 99%-to-completion, etc at this point depending on how fast the engine was assembled.

这是怎么设想的非阻塞,异步code。 1号线的主线程得到继续,而不必等待2号线完成第一突突一起。但这种流水线隐喻需要两个组装线,或两个线程,但JS是单线程的。

This is how I envisioned non-blocking, async code. The main thread of Line 1 gets to continue to chug along without having to wait for Line 2 to finish first. But this assembly line metaphor requires two assembly lines, or two threads, but JS is single-threaded.

所以现在我很困惑。

推荐答案

在短,运行时有一个事件循环,还挺模拟异步在1个线程。
在久了,我发现这个视频和文字是一个很好的解释:
http://2014.jsconf.eu/speakers/philip-roberts-what-the-heck-is-the-event-loop-anyway.html

In short, the runtime has an event loop that kinda simulates async in 1 thread. In long, I found this video and text to be a good explanation: http://2014.jsconf.eu/speakers/philip-roberts-what-the-heck-is-the-event-loop-anyway.html

这篇关于如何既JS非阻塞/异步但单线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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