Node.js Worker.isMainThread Property
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
// Node.js program to demonstrate // the Worker.isMainThread API // Importing worker_thread module const { Worker, isMainThread } = require( 'worker_threads' ); // Checking if the current thread is inside the // Main thread or not by using IsMainThread API 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
// Node.js program to demonstrate the // Worker.isMainThread API // Importing worker_thread module const { Worker, isMainThread } = require( 'worker_threads' ); // Checking if the current thread is // inside the main thread or not // by using IsMainThread API if (isMainThread) { // This re-loads the current file // inside a Worker instance. 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
Please Login to comment...