Skip to content

Commit

Permalink
feat: support fork app worker by worker_threads
Browse files Browse the repository at this point in the history
  • Loading branch information
hyj1991 committed Oct 30, 2022
1 parent fab0c80 commit f4721a7
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 3 deletions.
2 changes: 1 addition & 1 deletion lib/utils/mode/impl/worker_threads/agent.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ class AgentUtils extends BaseAgentUtils {
async kill() {
const worker = this.#worker;
if (worker) {
this.log('[master] kill agent worker(worker_threads) by worker.terminate()');
this.log(`[master] kill agent worker#${this.#id} (worker_threads) by worker.terminate()`);
this.clean();
worker.terminate();
}
Expand Down
68 changes: 66 additions & 2 deletions lib/utils/mode/impl/worker_threads/app.js
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 };

0 comments on commit f4721a7

Please sign in to comment.