Thread Creation and Management
In JavaScript, threads are created and managed using worker threads. Worker threads allow you to execute JavaScript code in a separate thread, without blocking the main thread. This is particularly useful for running computationally intensive tasks, performing I/O operations, or executing tasks in parallel.
To use worker threads in JavaScript, you can utilize the worker_threads
module, which provides the Worker
class for creating and managing worker threads.
Here's an example of creating and managing a worker thread:
JAVASCRIPT
1const { Worker } = require('worker_threads');
2
3function createWorkerThread(scriptPath) {
4 const worker = new Worker(scriptPath);
5
6 worker.on('message', (message) => {
7 console.log('Message from worker:', message);
8 });
9
10 worker.on('error', (error) => {
11 console.error('Error in worker:', error);
12 });
13
14 worker.on('exit', (code) => {
15 if (code !== 0)
16 console.error('Worker stopped with exit code', code);
17 });
18
19 return worker;
20}
21
22const worker = createWorkerThread('./worker.js');
23
24worker.postMessage('Hello from main thread!');
xxxxxxxxxx
24
const { Worker } = require('worker_threads');
function createWorkerThread(scriptPath) {
const worker = new Worker(scriptPath);
worker.on('message', (message) => {
console.log('Message from worker:', message);
});
worker.on('error', (error) => {
console.error('Error in worker:', error);
});
worker.on('exit', (code) => {
if (code !== 0)
console.error('Worker stopped with exit code', code);
});
return worker;
}
const worker = createWorkerThread('./worker.js');
worker.postMessage('Hello from main thread!');
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment