本文介绍了单线程事件循环与Node.JS中的多线程非阻塞工作器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Node.JS最大的优点是它具有非阻塞性。它是单线程的,因此不需要为每个新的传入连接生成一个新线程。

Node.JS biggest advantage is it's non blocking nature. It's single threaded, so it doesn't need to spawn a new thread for each new incoming connection.

在事件循环(实际上是单线程)后面,有一个非阻塞工作者。这个东西不再是单线程了,所以(据我所知)它可以为每个任务生成一个新线程。

Behind the event-loop (which is in fact single threaded), there is a "Non blocking Worker". This thing is not single threaded anymore, so (as far as I understood) it can spawn a new thread for each task.

也许我误解了一些东西,但究竟是哪里优势。如果有很多任务要处理,那么非阻塞工作会不会变成阻止工作者?

Maybe I misunderstood something, but where exactly is the advantage. If there are to many tasks to handle, wouldn't be the Non Blocking Working turn into a Blocking Worker?

谢谢
Christian

ThanksChristian

推荐答案

,节点的非阻塞I / O背后的魔力。

You need to read about libuv, the "magic" behind node's non-blocking I/O.

从libuv书中拿走的重要一点是libuv使用主机操作系统 ; 它并不是为每个连接创建一个新线程

The important thing to take away from the libuv book is that libuv uses the host OS's asynchronous I/O facilities; it does not simply create a new thread for every connection.

libuv告诉操作系统它想知道任何更改(连接状态) ,收到的数据等)发生在一组特定的套接字上。然后由OS来处理管理连接。操作系统本身可以创建一个或多个线程来实现这一点,但这不是我们关注的问题。 (并且它肯定不会为每个连接创建一个线程。)

libuv tells the OS that it would like to know about any changes (connection state, data received, etc) that happen on a particular set of sockets. It is then up to the OS to deal with managing the connections. The OS itself may create one or more threads to accomplish that, but that's not our concern. (And it certainly won't create a thread for every connection.)

对于其他类型的操作,例如对C库的调用可能计算成本很高(即加密), libuv提供了一个线程池,可以在其上运行这些操作。由于它是一个线程池,因此您不必担心线程计数在没有绑定的情况下增长。当池完全忙碌时,操作就会排队。

For other types of operations like calls to C libraries that may be computationally expensive (ie crypto), libuv provides a thread pool on which those operations may run. Since it is a thread pool, again you don't have to worry about thread count growing without bound. When the pool is fully busy, operations are queued.

所以是的,JavaScript在单个线程上运行。是的,node(通过libuv)在后台产生许多线程来完成工作,因此它不需要阻止JavaScript线程。但是,线程计数始终是受控制的,并且I / O通常甚至不会获得自己的节点分配线程,因为它由操作系统处理。

So yes, JavaScript runs on a single thread. Yes, node (via libuv) spawns many threads in the background to do work so that it need not block the JavaScript thread. However, the thread count is always controlled, and I/O generally doesn't even get its own node-allocated thread because that's handled by the OS.

这篇关于单线程事件循环与Node.JS中的多线程非阻塞工作器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 21:16