Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Is Node.js a single threaded program?

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "is Node.js a single-threaded program?" the content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "is Node.js a single-threaded program?"

Node.js is a single-threaded program

All the Javsacript,V8 and event loop we wrote run in the same thread, that is, main thrad.

Hey, doesn't this mean that node is single-threaded?

But maybe you don't know that many modules in node are backed by C++ code.

Although node does not expose users the authority to control thread, C++ can use multithreading.

So when will node use multithreading?

If a node method calls C++ 's synchronization method behind it, it will all run in the main thread.

If a node method calls C++ 's asynchronous method behind it, sometimes it doesn't run in the main thread.

Talk is cheap, show me the code.

Synchronization method, running in main thread

Many of the modules related to crypto here are written by C++. The following program is a function that calculates hash and is generally used to store passwords.

Import {pbkdf2Sync} from "crypto"; const startTime = Date.now (); let index = 0 for (index = 0; index)

< 3; index++) { pbkdf2Sync("secret", "salt", 100000, 64, "sha512"); const endTime = Date.now(); console.log(`${index} time, ${endTime - startTime}`);}const endTime = Date.now();console.log(`in the end`); 输出的时间, 0 time, 44 1 time, 902 time, 134in the end 可以看到每次大概都是花费~45ms,代码 main thread 上顺序执行。 注意最后的输出是谁? 注意这里一次 hash 在我的 cpu 需要~45ms。 异步 pbkdf2 方法,不跑在 main thread 里面import { cpus } from "os";import { pbkdf2 } from "crypto";console.log(cpus().length);let startTime = console.time("time-main-end");for (let index = 0; index < 4; index++) { startTime = console.time(`time-${index}`); pbkdf2("secret", `salt${index}`, 100000, 64, "sha512", (err, derivedKey) =>

{if (err) throw err; console.timeEnd (`time-$ {index} `);});} console.timeEnd ("time-main-end")

Time of output

Time-main-end: 0.31mstime-2: 45.646mstime-0: 46.055mstime-3: 46.846mstime-1: 47.159ms

You can see that main thread ends early, but the time for each calculation is 45ms. You should know that the time for a cpu to calculate hash is 45ms. Here node definitely uses multiple threads for hash calculation.

If I change the number of calls here to 10, then the time is as follows, and you can see that the time increases as the CPU core is used up. Once again, it proves that node definitely uses multiple threads for hash calculations.

Time-main-end: 0.451mstime-1: 44.977mstime-2: 46.069mstime-3: 50.033mstime-0: 51.381mstime-5: 96.429ms / / Note here, time-7: 101.61mstime-4: 113.535mstime-6: 121.429mstime-9: 151.035mstime-8: 152.585ms has been added since the fifth time.

Although it has been proved here, node definitely enables multithreading. But there's a little problem? The CPU of my computer is AMD R5-5600U, with 6 core 12 threads. But why did time increase from the fifth time? node didn't make full use of my CPU?

What is the reason?

Node uses a predefined thread pool, which defaults to a size of 4. 0.

Export UV_THREADPOOL_SIZE=6

Let's look at an example.

HTTP requestimport {request} from "https"; const options = {hostname: "www.baidu.com", port: 443,path: "/ img/PC_7ac6a6d319ba4ae29b38e5e4280e9122.png", method: "GET",}; let startTime = console.time (`main`); for (let index = 0; index)

< 15; index++) { startTime = console.time(`time-${index}`); const req = request(options, (res) =>

{console.log (`res.statusCode: ${res.statusCode} `); console.timeEnd (`time-$ {index}`); res.on ("data", (d) = > {/ / process.stdout.write (d);});}); req.on ("error", (error) = > {console.error (error);}); req.end ();} console.timeEnd ("main") Main: 13.927mstime-2: 83.247mstime-4: 89.641mstime-3: 91.497mstime-12: 91.661mstime-5: 94.677ms.time-8: 134.026mstime-1: 143.906mstime-13: 140.914mstime-10: 144.088ms

The main program ended early here, and here I started http request to download images 15 times, and their time did not increase exponentially and seemed unaffected by the thread pool / cpu.

Why? Is Node using thread pools or not?

If the async method of C++ behind Node, we will first try whether there is kernel async support. For example, use epoll (Linux) for the network here. If the kernel does not provide async mode, Node will use its own thread pool.

Therefore, although the http request is asynchronous, it is implemented by the kernel. When the kernel completes, it will notify the Clearkeeper, and C++ will notify the main thread to process the callback.

So which asynchronous methods of Node use thread pools? Which ones won't?

Native Kernal Async

TCP/UDP server client

Unix Domain Sockets (IPC)

Pipes

Dns.resolveXXX

Tty input (stdin etc)

Unix signals

Child process

Thread pool

Fs.*

Dns.lookup

Pipe (edge case)

This is also the entry point for most Node optimizations.

But how does this combine with the most important Event Loop?

Event Loop

I believe everyone is very familiar with Event loop. Event loop is like a distributor.

If you encounter an ordinary javascript program or callback, give it to V8 to handle.

If the back of the synchronization method is written by C++, give it to the synchronization method and run in main thread.

If the back of the asynchronous method is written by C++, if there is kernel asynchronous support, give it to the kernel from main thread to handle.

If the back of the asynchronous method is written by C++, if there is no kernel asynchronous support, give it to thread pool from main thread.

Both thread pool and kernel will return the result to event loop. If javascript callback is registered, it will be processed by V8.

And then cycle around until there's nothing to deal with.

So Node is not exactly a single-threaded program.

Thank you for reading, the above is the content of "Node.js is a single-threaded program?" after the study of this article, I believe you have a deeper understanding of the problem that Node.js is a single-threaded program, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report