Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

node.js - Can we achieve parallel processing using multiple cpu cores in NodeJs with worker threads?

I know "cluster" and "child_process" can use multiple cores of a CPU so that we can achieve true parallel processing.

I also know that the async event loop is single-threaded so we can only achieve concurrency.

My question is about worker_threads:

Assume that My computer has 4 core CPU And I'm executing a nodejs script. The script creates three worker threads.

Would the three worker thread make use of the remaining 3 cores in the CPU to achieve parallelism?

or the three worker threads will only use the main core and the remaining 3 core are not used just like the event loop?

question from:https://stackoverflow.com/questions/66067300/can-we-achieve-parallel-processing-using-multiple-cpu-cores-in-nodejs-with-worke

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Would the three worker thread make use of the remaining 3 cores in the CPU to achieve parallelism?

Yes, you can achieve parallelism. The actual CPU allocation is, of course, up to the operating system, but these will be true OS threads and will be able to take advantage of multiple CPUs.

or the three worker threads will only use the main core and the remaining 3 core are not used just like the event loop?

No. Each worker thread can use a separate CPU. Each thread has its own separate event loop.

The main time that the four threads will not be independent is when they wish to communicate with each other via messaging because those messages will go through the recipient's event loop. So, if thread A sends a message to the main thread, then that message will go into the main thread's event queue and won't be received by the main loop until the main loop gets back to the event loop retrieve that next message from the event queue. The same is true for the reverse. If you sent a message from the main thread to thread A, but thread A was busy executing a CPU intensive task, that message won't be received until thread A gets back to the event loop (e.g. finishes its CPU-intensive task).

Also, be careful if your threads are doing I/O (particularly disk I/O) as they may be competing for access to those resources and may get stuck waiting for other threads to finish using a resource before they can proceed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...