Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

node
worker
communitycreator
thread property

What is worker.isMainThread in Node?

Ayush Trivedi

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

In this shot, we will learn about the Node thread property isMainThread, which is provided by the worker_threads library in Node.

The library worker_threads provides us APIs which let the developer run code in different threads that run parallel to each other.

isMainThread is a property in the worker_threads library which returns a Boolean value:

  • true: When code is running in the main thread.
  • false: When the code is running in the child threads.

Code example 1

We will write simple code which finds if the current code is running in the main thread or not using the property isMainThread.

const { Worker, isMainThread } = require('worker_threads');
console.log(isMainThread);

Code explanation

  • In line 1, we will require and import the property isMainThread from the library worker_threads.

  • In line 3, we will console log the property isMainThread, which returns a Boolean value.

Output:

Here, the output will be true because it is the main thread.

Code example 2

const { Worker, isMainThread } = require('worker_threads');
if(isMainThread){
new Worker(__filename);
}
console.log(isMainThread);

Code explanation

  • In line 1, we will require and import the property isMainThread from the library worker_threads.

  • In line 3, we will create a new thread using Worker() and pass the current file. It will re-load the file in the new thread.

  • In line 5, we will console log the property isMainThread, which returns a boolean value.

Output:

In this code example, the output will be false because of the new thread created.

RELATED TAGS

node
worker
communitycreator
thread property

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring