Node.js worker_threads module
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:
- CPU-intensive tasks block the event loop
- The performance of multi-core CPUs cannot be fully utilized
- 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
- Main thread: The main execution thread of the application, responsible for creating and managing worker threads
- 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
- Proper use of: Do not create a thread for every small task; thread creation has overhead
- Error handling: Always listen for the 'error' and 'exit' events of worker threads
- Resource cleanup: Ensure worker threads exit correctly after completing their tasks
- Communication optimization: Minimize the amount of data communicated between threads
- CPU affinity: For long-running threads, consider setting CPU affinity
Performance considerations
- Thread Pool: For frequent short-term tasks, consider using a thread pool pattern
- Load balancing: Distribute worker threads evenly across multi-core systems
- Memory Usage: Each worker thread has its own V8 instance and memory space
Common questions
When should you use worker_threads?
- CPU-intensive computation
- When you need to process multiple tasks in parallel
- When you need to leverage multi-core CPUs
What is the difference between the worker_threads and cluster modules?
clustercluster creates multiple Node.js processesworker_threadsworker_threads creates threads that share the same process
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.
Node.js Built-in Modules