Visv M
Visv M

Reputation: 481

Process vs Worker vs Thread vs Task vs Pool in Node.js

What is Process, Worker, Thread, Task, Pool in Node.js from a programmer point of view?

I went through a lot of material, but difficult to understand quickly for a beginner programmer. Here is a quick summary

Upvotes: 10

Views: 6577

Answers (1)

Visv M
Visv M

Reputation: 481

A Node.js process is created when run a Node.js program like node app.js (or the child process created through child_process or cluster modules). Each process will have its own memory and resources

Worker is a Node.js built-in module which takes your module (.js) as an input and creates worker object, inside a process, that executes asynchronously.

//app.js
//TODO add modules
const { Worker } = require('worker_threads');

//TODO wrap the below code into your code

const worker = new Worker('./task_processor.js');
const workerMaxLifetime = 10000;

//Send message to worker
worker.postMessage('Message to thread');
//Receive message from worker
worker.on('message', (message) => { console.log(' App:', message); });
//Terminate worker
setTimeout(() => { worker.terminate(); }, workerMaxLifetime);

Task is your module (.js) where you write the code to run as a Thread. Actually, we should call it 'Task Processor'

//task_processor.js
//TODO add modules
const { parentPort } = require('worker_threads');
//TODO wrap the below code into your code

//Receive message from App
parentPort.on('message', (task_input) => {
  //Send message to App
  parentPort.postMessage(task_input.a + task_input.b);
});

Thread is nothing but the worker in execution.

Pool is a wrapper .js file which create/terminate worker objects and facilitates communication between App and worker. Worker pool is not mandatory though most real world scenarios implements pools where worker thread concept is implemented. Example

Node.js module is a .js file

App: The main(or default) thread in a process is also referred as App

Process vs Worker: Each process will have its own memory and resources, whereas worker uses the same memory and resources of the process from which it is created.

Upvotes: 11

Related Questions