Home > Web Front-end > JS Tutorial > body text

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

青灯夜游
Release: 2022-02-28 19:47:38
forward
3881 people have browsed it

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.

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:

//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 :

//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!

Related labels:
source:juejin.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!