-
Notifications
You must be signed in to change notification settings - Fork 59
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: support fork app worker by worker_threads
- Loading branch information
Showing
2 changed files
with
67 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,69 @@ | ||
'use strict'; | ||
|
||
// worker_threads not support send handle | ||
const workerThreads = require('worker_threads'); | ||
const { BaseAppWorker, BaseAppUtils } = require('../../base/app'); | ||
|
||
module.exports = require('../process/app'); | ||
class AppWorker extends BaseAppWorker { | ||
#id = 0; | ||
|
||
get id() { | ||
return this.#id; | ||
} | ||
|
||
get workerId() { | ||
return this.instance.threadId; | ||
} | ||
|
||
get exitCode() { | ||
return this.instance.exitCode; | ||
} | ||
|
||
send(...args) { | ||
this.instance.postMessage(...args); | ||
} | ||
|
||
clean() { | ||
this.instance.removeAllListeners(); | ||
} | ||
|
||
static on(event, callback) { | ||
workerThreads.parentPort.on(event, callback); | ||
} | ||
|
||
static send(data) { | ||
workerThreads.parentPort.postMessage(data); | ||
} | ||
|
||
static kill() { | ||
process.exit(1); | ||
} | ||
|
||
static gracefulExit(options) { | ||
const { beforeExit } = options; | ||
process.on('exit', async code => { | ||
if (typeof beforeExit === 'function') { | ||
await beforeExit(); | ||
} | ||
process.exit(code); | ||
}); | ||
} | ||
} | ||
|
||
class AppUtils extends BaseAppUtils { | ||
#workers = []; | ||
|
||
fork() { | ||
|
||
return this; | ||
} | ||
|
||
async kill() { | ||
for (const worker of this.#workers) { | ||
this.log(`[master] kill app worker#${worker.id} (worker_threads) by worker.terminate()`); | ||
worker.removeAllListeners(); | ||
worker.terminate(); | ||
} | ||
} | ||
} | ||
|
||
module.exports = { AppWorker, AppUtils }; |