In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces "Node.js + worker_threads how to achieve multithreading" related knowledge, editor through the actual case to show you the operation process, the operation method is simple and fast, practical, I hope that this "Node.js + worker_threads how to achieve multithreading" article can help you solve the problem.
In general, Node.js is considered to be single-threaded. The main thread executes the program code step by step according to the coding order. Once the synchronous code is blocked, the main thread will be occupied and the subsequent execution of the program code will be stuck. Yes, Node.js 's single thread means that the main thread is "single thread".
In order to solve the problems caused by single threading, the protagonist worker_threads of this article appears. Worker_threads first appeared as an experimental feature in Node.js v10.5.0 and requires a command line with-- experimental-worker to use. It will not be officially available until v12.11.0 stable version.
This article will introduce how to use worker_threads and use worker_threads to execute Fibonacci series as a practical example.
precondition
To read and eat this article, you need to have:
Node.js v12.11.0 and above are installed
Master the basic knowledge of JavaScript synchronous and asynchronous programming
Master the working principle of Node.js
Worker_threads introduction
The worker_threads module allows threads that execute JavaScript in parallel.
Worker threads are useful for performing CPU-intensive JavaScript operations. They are not very helpful to the intensive work of Istroke O. Node.js 's built-in asynchronous Imax O operation is more efficient than worker threads.
Unlike child_process or cluster, worker_threads can share memory. They are achieved by transferring ArrayBuffer instances or sharing SharedArrayBuffer instances.
Worker_threads has been proven to be the best solution to take full advantage of CPU performance due to the following features:
They run a single process with multiple threads.
Each thread executes an event loop.
Each thread runs a single instance of the JS engine.
Each thread executes a single instance of Nodejs.
How worker_threads works
Worker_threads works by executing the script file specified by the main thread. Each thread executes in isolation from other threads. However, these threads can pass messages back and forth through the message channel.
The main thread uses the worker.postMessage () function to use the message channel, while the worker thread uses the parentPort.postMessage () function.
Learn more about it through the official sample code:
Const {Worker, isMainThread, parentPort, workerData} = require ('worker_threads'); if (isMainThread) {module.exports = function parseJSAsync (script) {return new Promise ((resolve, reject) = > {const worker = new Worker (_ _ filename, {workerData: script}); worker.on (' message', resolve); worker.on ('error', reject) Worker.on ('exit', (code) = > {if (code! = = 0) reject (new Error (`Worker stopped with exit code ${code} `));};} else {const {parse} = require (' some-js-parsing-library'); const script = workerData; parentPort.postMessage (parse (script));}
Both the main thread and the worker thread of the above code use the same file as the execution script (_ _ filename is the current execution file path), and isMainThread is used to distinguish the runtime logic between the main thread and the worker thread. When the module exposes the method parseJSAsync is called, the child worker thread will be derived to execute the call parse function.
Specific use of worker_threads
Use specific examples to introduce the use of worker_threads in this section
Create the worker thread script file workerExample.js:
Const {workerData, parentPort} = require ('worker_threads') parentPort.postMessage ({welcome: workerData})
Create the main thread script file main.js:
Const {Worker} = require ('worker_threads') const runWorker = (workerData) = > {return new Promise ((resolve, reject) = > {/ / introduce workerExample.js `worker thread` script file const worker = new Worker ('. / workerExample.js', {workerData}); worker.on ('message', resolve); worker.on (' error', reject) Worker.on ('exit', (code) = > {if (code! = = 0) reject (new Error (`stopped with ${code} exit code`));})} const main = async () = > {const result = await runWorker (' hello worker threads') console.log (result);} main (). Catch (err = > console.error (err))
Console command line execution:
Node main.js
Output:
{welcome: 'hello worker threads'} worker_threads Fibonacci sequence
In this section, let's take a look at a CPU-intensive example that generates a Fibonacci sequence.
If you complete this task without a worker thread, the main thread will be blocked as the nth duration increases.
Create a worker thread script file worker.js
Const {parentPort, workerData} = require ("worker_threads"); parentPort.postMessage (getFibonacciNumber (workerData.num)) function getFibonacciNumber (num) {if (num = 0) {return 0;} else if (num = 1) {return 1;} else {return getFibonacciNumber (num-1) + getFibonacciNumber (num-2);}}
Create the main thread script file main.js:
Const {Worker} = require ("worker_threads"); let number = 30 num Const worker = new Worker (". / worker.js", {workerData: {num: number}}); worker.once ("message", result = > {console.log (`${number} th Fibonacci Result: ${result}`); worker.on ("error", error = > {console.log (error);}); worker.on ("exit", exitCode = > {console.log (`It exited with code ${exitCode} `)) }) console.log ("Execution in main thread")
Console command line execution:
Node main.js
Output:
Execution in main thread30th Fibonacci Result: 832040It exited with code 0
In the main.js file, we create a worker thread from an instance of the class, Worker, as we saw in the previous example.
To get the results, we monitored three events.
The message sends a message in response to the worker thread.
The event that exit triggers when the worker thread stops executing.
Triggered when an error occurs in error.
We're on the last line, main.js.
Console.log ("Execution in main thread")
The output from the console shows that the main thread is not blocked by the Fibonacci sequence operation.
Therefore, as long as we deal with CPU-intensive tasks in the worker thread, we can continue to work on other tasks without worrying about blocking the main thread.
This is the end of the introduction of "how to achieve multithreading in Node.js + worker_threads". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.