Worker.isMainThread属性是worker_threads模块中Worker类的内置应用程序编程接口,用于检查当前线程是否在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
相关用法
- Node.js GM charcoal()用法及代码示例
- Node.js GM blur()用法及代码示例
- Node.js GM sharpen()用法及代码示例
- Node.js GM drawLine()用法及代码示例
- Node.js GM drawArc()用法及代码示例
- Node.js GM drawPolyline()用法及代码示例
- Node.js GM drawBezier()用法及代码示例
- Node.js GM drawCircle()用法及代码示例
注:本文由纯净天空筛选整理自RohitPrasad3大神的英文原创作品 Node.js Worker.isMainThread Property。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。