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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。