Message Passing: The Basics
Since Worker Threads don’t share the same execution context, they need to communicate using messages.
This is done via the postMessage()
and message
event listener.
Each worker has a message port that allows it to send and receive data from the main thread.
Think of it like a walkie-talkie—except instead of shouting, we send structured JSON objects.
Sending and Receiving Messages
Let’s start with a simple example of message passing between a main thread and a worker.
Main Thread (index.js)
|
|
Worker Thread (worker.js)
|
|
Output
|
|
See?
They’re getting along just fine.
✨
Sending Complex Data Structures
Worker Threads support structured cloning, meaning you can send objects, arrays, and even TypedArrays!
Main Thread Example
|
|
Worker Thread Example
|
|
This allows for more complex and meaningful interactions between threads.
Sharing Memory Between Threads
Sometimes, sending data via messages can be slow for large datasets.
Instead, you can use SharedArrayBuffer to allow direct memory access across threads.
Main Thread Example
|
|
Worker Thread Example
|
|
With SharedArrayBuffer, threads can modify the same memory region without the overhead of message passing.
Handling Multiple Workers
What if you have multiple workers?
You can assign different tasks to each worker and handle their responses separately.
Main Thread Example
|
|
This setup lets you efficiently distribute workloads across multiple threads.
When to Use Message Passing vs.
Shared Memory
Use Case | Best Approach |
---|---|
Small data or JSON objects | Message passing (postMessage) |
Large datasets | SharedArrayBuffer |
Multiple independent tasks | Separate workers |
High-speed memory access | Shared memory |
Conclusion
Worker Threads communicate via message passing using
postMessage()
andmessage
event listeners.They support structured data like objects, arrays, and buffers.
For faster data sharing, use
SharedArrayBuffer
to avoid serialization overhead.Multiple workers can process tasks in parallel, improving performance for CPU-intensive workloads.