Table of Contents
Multi-process and multi-threading in node.js
Home Web Front-end JS Tutorial An article to talk about node's multi-processing and multi-threading

An article to talk about node's multi-processing and multi-threading

Feb 28, 2022 pm 07:47 PM
node Multithreading multi-Progress

This article will take you to understand node.js, introduce multi-process and multi-threading in node, and compare multi-process and multi-thread. I hope it will be helpful to everyone!

An article to talk about node's multi-processing and multi-threading

Multi-process and multi-threading in node.js

In node.js, the execution of javascript code is single-threaded Execution, but Node itself is actually multi-threaded.

An article to talk about nodes multi-processing and multi-threading

The node itself is divided into three layers

The first layer, Node .js standard library, this part is written in Javascript, that is, the API that we can call directly during use, which can be seen in the lib directory in the source code.

The second layer, Node bindings, this layer is the key for Javascript to communicate with the underlying C/C. The former calls the latter through bindings and exchanges data with each other. It is the first layer and Third level bridge.

The third layer is the key to supporting the operation of Node.js. It is implemented by C/C and is some of the underlying logic implemented by node.

Among them, the third layer of Libuv provides Node.js with cross-platform, thread pool, event pool, asynchronous I/O and other capabilities, which is the key to making Node.js so powerful.

Because Libuv provides an event loop mechanism, JavaScript will not block in terms of io processing. Therefore, when we use node to build web services, we do not need to worry about excessive io volume causing other requests to be blocked.

However, the execution of non-io tasks is executed in the node main thread, which is a single-thread execution task. If there are very time-consuming synchronous computing tasks, it will block the execution of other codes.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

const Koa = require('koa');

const app = new Koa();

 

app.use(async (ctx) => {

    const url = ctx.request.url;

    if (url === '/') {

        ctx.body = {name: 'xxx', age: 14}

    }

    if(url==='/compute'){

        let sum=0

        for (let i = 0; i <100000000000 ; i++) {

        sum+=i   

        }

        ctx.body={sum}

    }

})

app.listen(4000, () => {

    console.log(&#39;http://localhost:4000/ start&#39;)

})

Copy after login

In the above code, if http requests /compute, node will call the cpu to perform a large number of calculations. At this time, if other http requests come in, blocking will occur. .

So how to solve this problem?

There are two solutions, one is to use children_process or cluster to start multiple processes for calculation, and the other is to use worker_thread Turn on multi-threading for calculation

Multi-process vs multi-thread

Compare multi-threading and multi-process:

AttributesMultiple processesMultiple threadsCompare
Data Data sharing is complex and requires IPC; data is separated and synchronization is simpleBecause process data is shared, data sharing is simple and synchronization is complexEach has its own merits
CPU, memoryOccupies a lot of memory, complex switching, low CPU utilizationOccupies little memory, simple switching, high CPU utilization Multi-threading is better
Destruction and switchingCreation, destruction, and switching are complex and slowCreation, destruction, and switching are simple and fastMulti-threading is better
codingSimple coding, convenient debuggingCoding, complex debuggingCoding, Complex debugging
ReliabilityProcesses run independently and will not affect each otherThreads share the same fateMultiple processes more Good
DistributedCan be used for multi-machine multi-core distribution, easy to expandCan only be used for multi-core distribution Multi-process is better

Use multi-threading to solve the calculation problem of the above code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

//api.js

const Koa = require(&#39;koa&#39;);

const app = new Koa();

 

const {Worker} = require(&#39;worker_threads&#39;)

app.use(async (ctx) => {

    const url = ctx.request.url;

    if (url === &#39;/&#39;) {

        ctx.body = {name: &#39;xxx&#39;, age: 14}

    }

 

    if (url === &#39;/compute&#39;) {

        const sum = await new Promise(resolve => {

            const worker = new Worker(__dirname+&#39;/compute.js&#39;)

          //接收信息

            worker.on(&#39;message&#39;, data => {

                resolve(data)

            })

        })

        ctx.body = {sum}

 

    }

})

app.listen(4000, () => {

    console.log(&#39;http://localhost:4000/ start&#39;)

})

 

 

 

//computer.js

const {parentPort}=require(&#39;worker_threads&#39;)

let sum=0

for (let i = 0; i <1000000000 ; i++) {

    sum+=i

}

//发送信息

parentPort.postMessage(sum)

Copy after login

Here is the official document,worker_threads

https://nodejs.org/dist/latest-v16.x/docs/api/worker_threads.html

Use multiple processes to solve the calculation problem of the above code :

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

//api.js

const Koa = require(&#39;koa&#39;);

const app = new Koa();

const {fork} = require(&#39;child_process&#39;)

 

app.use(async (ctx) => {

    const url = ctx.request.url;

    if (url === &#39;/&#39;) {

        ctx.body = {name: &#39;xxx&#39;, age: 14}

    }

 

    if (url === &#39;/compute&#39;) {

        const sum = await new Promise(resolve => {

          const worker =fork(__dirname+&#39;/compute.js&#39;)

            worker.on(&#39;message&#39;, data => {

                resolve(data)

            })

        })

        ctx.body = {sum}

 

    }

})

app.listen(4000, () => {

    console.log(&#39;http://localhost:4000/ start&#39;)

})

 

//computer.js

let sum=0

for (let i = 0; i <1000000000 ; i++) {

    sum+=i

}

process.send(sum)

Copy after login

Here is the official documentation, child_process

https://nodejs.org/dist/latest-v16.x/docs/api/child_process .html

For more node-related knowledge, please visit: nodejs tutorial!

The above is the detailed content of An article to talk about node's multi-processing and multi-threading. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1658
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
C++ function exceptions and multithreading: error handling in concurrent environments C++ function exceptions and multithreading: error handling in concurrent environments May 04, 2024 pm 04:42 PM

Function exception handling in C++ is particularly important for multi-threaded environments to ensure thread safety and data integrity. The try-catch statement allows you to catch and handle specific types of exceptions when they occur to prevent program crashes or data corruption.

How to implement multi-threading in PHP? How to implement multi-threading in PHP? May 06, 2024 pm 09:54 PM

PHP multithreading refers to running multiple tasks simultaneously in one process, which is achieved by creating independently running threads. You can use the Pthreads extension in PHP to simulate multi-threading behavior. After installation, you can use the Thread class to create and start threads. For example, when processing a large amount of data, the data can be divided into multiple blocks and a corresponding number of threads can be created for simultaneous processing to improve efficiency.

Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Mar 05, 2025 pm 05:57 PM

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

How can concurrency and multithreading of Java functions improve performance? How can concurrency and multithreading of Java functions improve performance? Apr 26, 2024 pm 04:15 PM

Concurrency and multithreading techniques using Java functions can improve application performance, including the following steps: Understand concurrency and multithreading concepts. Leverage Java's concurrency and multi-threading libraries such as ExecutorService and Callable. Practice cases such as multi-threaded matrix multiplication to greatly shorten execution time. Enjoy the advantages of increased application response speed and optimized processing efficiency brought by concurrency and multi-threading.

How do PHP functions behave in a multi-threaded environment? How do PHP functions behave in a multi-threaded environment? Apr 16, 2024 am 10:48 AM

In a multi-threaded environment, the behavior of PHP functions depends on their type: Normal functions: thread-safe, can be executed concurrently. Functions that modify global variables: unsafe, need to use synchronization mechanism. File operation function: unsafe, need to use synchronization mechanism to coordinate access. Database operation function: Unsafe, database system mechanism needs to be used to prevent conflicts.

How to deal with shared resources in multi-threading in C++? How to deal with shared resources in multi-threading in C++? Jun 03, 2024 am 10:28 AM

Mutexes are used in C++ to handle multi-threaded shared resources: create mutexes through std::mutex. Use mtx.lock() to obtain a mutex and provide exclusive access to shared resources. Use mtx.unlock() to release the mutex.

Usage of JUnit unit testing framework in multi-threaded environment Usage of JUnit unit testing framework in multi-threaded environment Apr 18, 2024 pm 03:12 PM

There are two common approaches when using JUnit in a multi-threaded environment: single-threaded testing and multi-threaded testing. Single-threaded tests run on the main thread to avoid concurrency issues, while multi-threaded tests run on worker threads and require a synchronized testing approach to ensure shared resources are not disturbed. Common use cases include testing multi-thread-safe methods, such as using ConcurrentHashMap to store key-value pairs, and concurrent threads to operate on the key-value pairs and verify their correctness, reflecting the application of JUnit in a multi-threaded environment.

Challenges and countermeasures of C++ memory management in multi-threaded environment? Challenges and countermeasures of C++ memory management in multi-threaded environment? Jun 05, 2024 pm 01:08 PM

In a multi-threaded environment, C++ memory management faces the following challenges: data races, deadlocks, and memory leaks. Countermeasures include: 1. Use synchronization mechanisms, such as mutexes and atomic variables; 2. Use lock-free data structures; 3. Use smart pointers; 4. (Optional) implement garbage collection.

See all articles