Node.js Worker.isMainThread Property
Last Updated :
20 Jun, 2022
The Worker.isMainThread property an inbuilt application programming interface of class Worker within worker_threads module which is used to check if the current thread is running inside the worker thread or not.
Syntax:
const Worker.isMainThread
Parameters: This property does not accept any parameter.
Return Value: This property returns the Boolean value true if the current thread is running not inside the worker thread otherwise false.
Example 1: Filename: index.js
javascript
const { Worker, isMainThread } = require( 'worker_threads' );
if (isMainThread) {
console.log( 'OutSide Worker!2' );
console.log( '1' );
console.log( '2' );
console.log( '3' );
console.log(isMainThread);
}
|
Run the index.js file using the following command:
node index.js
Output:
OutSide Worker!2
1
2
3
true
Example 2: Filename: index.js
javascript
const { Worker, isMainThread }
= require( 'worker_threads' );
if (isMainThread) {
new Worker(__filename);
} else {
console.log( 'Inside Worker!2' );
console.log( '1' );
console.log( '2' );
console.log( '3' );
console.log(isMainThread);
}
|
Run the index.js file using the following command:
node index.js
Output:
Inside Worker!2
1
2
3
false
Reference: https://nodejs.org/dist/latest-v12.x/docs/api/worker_threads.html#worker_threads_worker_ismainthread
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...