📜  Node.js Worker.isMainThread 属性

📅  最后修改于: 2022-05-13 01:56:36.661000             🧑  作者: Mango

Node.js Worker.isMainThread 属性

Worker.isMainThread属性是 worker_threads 模块中 Worker 类的内置应用程序编程接口,用于检查当前线程是否在工作线程内运行。

句法:

const Worker.isMainThread

参数:此属性不接受任何参数。

返回值:如果当前线程不在工作线程内运行,则此属性返回布尔值 true,否则返回 false。

示例 1:文件名:index.js

// 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); 
}

使用以下命令运行index.js文件:

node index.js

输出:

OutSide Worker!2
1
2
3
true

示例 2:文件名:index.js

// 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); 
}

使用以下命令运行index.js文件:

node index.js

输出:

Inside Worker!2
1
2
3
false

参考: https://nodejs.org/dist/latest-v12.x/docs/api/worker_threads.html#worker_threads_worker_ismainthread