Home>Article>Web Front-end> A brief analysis of Node.js using worker_threads multi-threads for parallel processing

A brief analysis of Node.js using worker_threads multi-threads for parallel processing

Michael Jordan
Michael Jordan forward
2022-03-17 19:58:17 4557browse

How to use Node.js for parallel processing? The following article will introduce to you how to useNodemulti-threading for parallel processing. I hope it will be helpful to you!

A brief analysis of Node.js using worker_threads multi-threads for parallel processing

Many people can’t seem to understand how single-threaded NodeJS can compete with multi-threaded backends.

To find out why, we have to understand whatNodejsis really about being single-threaded.

JavaScript itself was originally created to do simple things like validate forms, make responses, etc. It wasn’t until 2009 that Node.js creator Ryan Dahl made writing server-side code in JavaScript a popular option. possible.

Server-side languages that support multithreading have various structures and constructs for synchronizing between threads and other thread-oriented features.

Supporting these things means that JavaScript needs to change the entire language, which also goes against the ideas of JavaScript's creators. So, to make pure JavaScript support multithreading, Dahl had to create a workaround. Let’s take a look!


How does Node.js work?

Node.js uses two kinds of threads: a main thread handled by an event loop and several secondary threads in a pool of worker threads.

Event loopNode.js mechanism for handling non-blocking I/O operations - even though JavaScript is single-threaded - they offload operations to the system when possible Go to the kernel. When a JavaScript operation blocks a thread, the event loop is also blocked.

Work poolis an execution model that spawns and processes separate threads, then executes tasks synchronously and returns the results to the event loop. The event loop then uses said result to execute the provided callback.

Basically, the worker pool handles asynchronous I/O operations - primarily interactions with the system disk and network. Some modules use worker pools out of the box, such as fs (I/O-heavy) or crypto (CPU-heavy). The worker pool is implemented in libuv, which causes a slight but almost negligible delay when Node needs to transfer data internally between JavaScript and C.

After understanding the meaning of event loop and work pool, let's look at the following code:

A brief analysis of Node.js using worker_threads multi-threads for parallel processing

In the above code, we do not have to wait for events synchronously. We delegate the task of reading the file to the worker pool and call the provided function with the result. Since the worker pool has its own thread, the event loop can continue executing normally while reading the file.


Let me introduce to you: worker_threads

With the release of Node.js 10.5.0, worker_threads appeared. It supports creating simple multi-threaded applications in JavaScript

worker_threads is a nodejs module package. A thread worker is a piece of code (usually taken from a file) generated in a separate thread.

It is important to note that the terms thread worker, worker and thread are often used interchangeably. They all refer to the same thing.

A brief analysis of Node.js using worker_threads multi-threads for parallel processing

#Worker threads in Node.js are useful for performing heavy JavaScript tasks. With the help of threads, Workers can easily run JavaScript code in parallel, making it faster and more efficient. We can complete heavy tasks without disturbing the main thread.

Worker threads were not introduced in the old version of Node.js. So, first update your Node.js to get started.

Now create two files to implement threads as follows:

File name: worker.js

const { workerData, parentPort } = require('worker_threads'); console.log(`Write-up on how ${workerData} wants to chill with the big boys`); parentPort.postMessage({ filename: workerData, status: 'Done' });

File name: index.js

const { Worker } = require('worker_threads'); const runSerice = (workerData) => { return new Promise((resolve, reject) => { const worker = new Worker('./worker.js', { workerData }); worker.on('message', resolve); worker.on('error', reject); worker.on('exit', (code) => { if (code !== 0) reject(new Error(`Worker Thread stopped with exit code ${code}`)); }); }); }; const run = async () => { const result = await runSerice('Tunde Ednut'); console.log(result); }; run().catch((err) => console.error(err));

Output:

A brief analysis of Node.js using worker_threads multi-threads for parallel processing

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

The above is the detailed content of A brief analysis of Node.js using worker_threads multi-threads for parallel processing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete