search
HomeWeb Front-endJS TutorialLet's talk about how Node.js + worker_threads implements multi-threading? (detailed explanation)

This article will take you to understand the worker_threads module, introduce how to use worker_threads to implement multi-threading in Node, and use worker_threads to execute the Fibonacci sequence as a practical example. I hope it will be helpful to everyone. !

Let's talk about how Node.js + worker_threads implements multi-threading? (detailed explanation)

Normally, Node.js is considered single-threaded. The main thread executes the program code step by step according to the coding sequence. Once the synchronization code is blocked, the main thread will be occupied, and subsequent execution of the program code will be stuck. That's right, the single thread of Node.js refers to the main thread being "single threaded".

In order to solve the problems caused by single thread, the protagonist of this article worker_threads appears. worker_threads first appeared as an experimental feature in Node.js v10.5.0. You need to bring --experimental-worker on the command line to use it. It will not be officially used until the v12.11.0 stable version.

This article will introduce how to use worker_threads, and use worker_threads to execute Fibonacci sequence as a practical example.

Prerequisites

To read and consume this article, you need to have:

  • InstalledNode.js v12.11.0 and above version
  • Master the basic knowledge of JavaScript synchronous and asynchronous programming
  • Master the working principle of Node.js

worker_threads introduction

worker_threads The module allows the use of threads that execute JavaScript in parallel.

Worker threads are useful for performing CPU-intensive JavaScript operations. They are not very helpful for I/O intensive work. Node.js's built-in asynchronous I/O operations are more efficient than worker threads.

Unlike child_process or cluster, worker_threads can share memory. They do this by transferring ArrayBuffer instances or sharing SharedArrayBuffer instances.

worker_threads have proven to be the best solution to fully utilize the CPU performance due to the following characteristics:

  • They run with multiple threads single process.

  • Each thread executes an event loop.

  • Run a single instance of the JS engine per thread.

  • Each thread executes a single Nodejs instance.

How worker_threads works

worker_threadsBy executing the main threadspecified script File to work. Each thread executes in isolation from other threads. However, these threads can pass messages back and forth through message channels.

Main threadUse worker.postMessage() function uses the message channel, while Worker threaduses parentPort.postMessage()function.

Enhance your understanding 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));
}

The above codeMain thread and Worker threadUse the same file as the execution script (__filename is the current execution file path), and use isMainThread to distinguish main thread and worker threadRuntime logic. When the module's externally exposed method parseJSAsync is called, a sub-worker thread will be spawned to execute the parse function.

Worker_threads specific use

In this section, we use specific examples to introduce the use of worker_threads

Create worker threadScript fileworkerExample.js:

const { workerData, parentPort } = require('worker_threads')
parentPort.postMessage({ welcome: workerData })

CreateMain threadScript filemain.js:

const { Worker } = require('worker_threads')

const runWorker = (workerData) => {
    return new Promise((resolve, reject) => {
        // 引入 workerExample.js `工作线程`脚本文件
        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))

Control Taiwan command line execution:

node main.js

Output:

{ welcome: 'hello worker threads' }

worker_threads Operation Fibonacci Sequence

In this section, let’s take a look at the CPU Intensive example, generating Fibonacci Sequence.

If this task is completed without a worker thread, the main thread will be blocked as the nth deadline increases.

CreateWorker threadScript fileworker.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);
    }
}

CreateMain threadScript filemain.js :

const {Worker} = require("worker_threads");

let number = 30;

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 thread
30th Fibonacci Result: 832040
It exited with code 0

In the main.js file, we start from the class Instance creates a worker thread, Worker as we saw in the previous example.

In order to get the results, we listen to 3 events,

  • message响应工作线程发出消息。
  • exit工作线程停止执行的情况下触发的事件。
  • error发生错误时触发。

我们在最后一行main.js

console.log("Execution in main thread");

通过控制台的输出可得,主线程并没有被斐波那契数列运算执行而阻塞。

因此,只要在工作线程中处理 CPU 密集型任务,我们就可以继续处理其他任务而不必担心阻塞主线程。

结论

Node.js 在处理 CPU 密集型任务时一直因其性能而受到批评。通过有效地解决这些缺点,工作线程的引入提高了 Node.js 的功能。

有关worker_threads的更多信息,请在此处访问其官方文档。

思考

文章结束前留下思考,后续会在评论区做补充,欢迎一起讨论。

  • worker_threads线程空闲时候会被回收吗?
  • worker_threads共享内存如何使用?
  • 既然说到线程,那么应该有线程池?

更多node相关知识,请访问:nodejs 教程

The above is the detailed content of Let's talk about how Node.js + worker_threads implements multi-threading? (detailed explanation). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft