Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Node.js worker_threads module

Node.js worker_threads module

Java FileNode.js Built-in Modules


Node.js's worker_threads The module allows developers to create multiple threads in Node.js applications. Unlike the traditional single-threaded Node.js model, this module lets you execute JavaScript code in separate threads, enabling true parallel processing.

Why multithreading is needed

Node.js is single-threaded by default, which means:

  1. CPU-intensive tasks block the event loop
  2. The performance of multi-core CPUs cannot be fully utilized
  3. Long-running computations reduce the responsiveness of applications

worker_threads The module solves these problems by allowing you to offload compute-intensive tasks to other threads.


Basic concepts

Main thread vs worker thread

  1. Main thread: The main execution thread of the application, responsible for creating and managing worker threads
  2. Worker threads: An independent execution thread created by the main thread for performing specific tasks

Inter-thread communication

Worker threads communicate with the main thread through message passing rather than shared memory. This approach avoids complex synchronization issues.


Core APIs

Main components of the worker_threads module

Example

const

{

  Worker

,

         

// Class used to create a new thread

  isMainThread

,

   

// Determine whether currently in the main thread

  parentPort

,

     

// Used to communicate with the parent thread

  workerData      

// Data passed when the thread is created

}

=

require

(

'worker_threads'

)

;


Usage examples

Create a simple worker thread

Main thread code (main.js):

Example

const

{

Worker

,

isMainThread

}

=

require

(

'worker_threads'

)

;

if

(

isMainThread

)

{

 

// Main thread code

  console.

log

(

'This is the main thread'

)

;

 

 

// Create a worker thread

 

const

worker

=

new

Worker

(

'./worker.js'

,

{

    workerData

:

{

      message

:

'Hello, worker thread!'

   

}

 

}

)

;

 

 

// Listen for messages from the worker thread

  worker.

on

(

'message'

,

(

msg

)

=>

{

    console.

log

(

`Received from worker thread

:

$

{

msg

}

`

)

;

 

}

)

;

 

  worker.

on

(

'error'

,

(

err

)

=>

{

    console.

error

(

'Worker thread error:'

,

err

)

;

 

}

)

;

 

  worker.

on

(

'exit'

,

(

code

)

=>

{

   

if

(

code

!==

0

)

{

      console.

error

(

`Worker thread exited abnormally with exit code

:

$

{

code

}

`

)

;

   

}

 

}

)

;

}

else

{

 

// Worker thread code

  require

(

'./worker.js'

)

;

}

Worker thread code (worker.js):

Example

const

{

parentPort

,

workerData

}

=

require

(

'worker_threads'

)

;

console.

log

(

'This is the worker thread'

)

;

console.

log

(

'Received message from the main thread:'

,

workerData.

message

)

;

// Simulate some work

setTimeout

(

(

)

=>

{

 

// Send a message to the main thread

  parentPort.

postMessage

(

'Work complete!'

)

;

}

,

2000

)

;


Advanced usage

Passing complex data

Example

// Main thread

const

worker

=

new

Worker

(

'./worker.js'

,

{

  workerData

:

{

    array

:

new

Uint8Array

(

[

1

,

2

,

3

,

4

]

)

,

    object

:

{

key

:

'value'

}

 

}

}

)

;

// Worker thread

console.

log

(

workerData.

array

)

;

 

// Uint8Array [ 1, 2, 3, 4 ]

console.

log

(

workerData.

object

)

;

// { key: 'value' }

Shared memory (SharedArrayBuffer)

Example

// Main thread

const

sharedBuffer

=

new

SharedArrayBuffer

(

16

)

;

const

arr

=

new

Uint8Array

(

sharedBuffer

)

;

arr

[

0

]

=

1

;

const

worker

=

new

Worker

(

'./worker.js'

,

{

  workerData

:

{

sharedBuffer

}

}

)

;

// Worker thread

const

{

sharedBuffer

}

=

workerData

;

const

arr

=

new

Uint8Array

(

sharedBuffer

)

;

console.

log

(

arr

[

0

]

)

;

// 1


Best Practices

  1. Proper use of: Do not create a thread for every small task; thread creation has overhead
  2. Error handling: Always listen for the 'error' and 'exit' events of worker threads
  3. Resource cleanup: Ensure worker threads exit correctly after completing their tasks
  4. Communication optimization: Minimize the amount of data communicated between threads
  5. CPU affinity: For long-running threads, consider setting CPU affinity

Performance considerations

  1. Thread Pool: For frequent short-term tasks, consider using a thread pool pattern
  2. Load balancing: Distribute worker threads evenly across multi-core systems
  3. Memory Usage: Each worker thread has its own V8 instance and memory space

Common questions

When should you use worker_threads?

What is the difference between the worker_threads and cluster modules?

How to debug worker threads?

Use --inspect and --inspect-brk flag, and assign a different debugging port to each worker thread.

Example

node

--inspect

=

9229

main.js


Summary

Node.js's worker_threads The module brings true multithreading capabilities to JavaScript, enabling developers to better leverage the performance of modern multi-core CPUs. By using worker threads appropriately, you can significantly improve the performance of CPU-intensive applications while maintaining Node.js's non-blocking I/O advantages.

Java FileNode.js Built-in Modules