Table of Contents
Prerequisites
How worker_threads works
Worker_threads specific use
worker_threads Operation Fibonacci Sequence
结论
思考
Home Web Front-end JS Tutorial Let's talk about how Node.js + worker_threads implements multi-threading? (detailed explanation)

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

Feb 11, 2022 pm 08:07 PM
node.js Multithreading

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));
}
Copy after login

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 })
Copy after login

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))
Copy after login

Control Taiwan command line execution:

node main.js
Copy after login
Copy after login

Output:

{ welcome: 'hello worker threads' }
Copy after login

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);
    }
}
Copy after login

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");
Copy after login

Console command line execution:

node main.js
Copy after login
Copy after login

Output:

Execution in main thread
30th Fibonacci Result: 832040
It exited with code 0
Copy after login

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");
Copy after login

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

因此,只要在工作线程中处理 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 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)

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.

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.

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.

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.

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.

Challenges and strategies for testing multi-threaded programs in C++ Challenges and strategies for testing multi-threaded programs in C++ May 31, 2024 pm 06:34 PM

Multi-threaded program testing faces challenges such as non-repeatability, concurrency errors, deadlocks, and lack of visibility. Strategies include: Unit testing: Write unit tests for each thread to verify thread behavior. Multi-threaded simulation: Use a simulation framework to test your program with control over thread scheduling. Data race detection: Use tools to find potential data races, such as valgrind. Debugging: Use a debugger (such as gdb) to examine the runtime program status and find the source of the data race.

See all articles