11import type { ModuleThread } from 'threads' ;
22import type { ModuleMethods } from 'threads/dist/types/master' ;
33import type { QueuedTask } from 'threads/dist/master/pool-types' ;
4-
54import { Pool } from 'threads' ;
65import Logger from '@matrixai/logger' ;
6+ import { CreateDestroy , ready } from '@matrixai/async-init/dist/CreateDestroy' ;
77import WorkerManagerInterface from './WorkerManagerInterface' ;
88import * as errors from './errors' ;
99
10+ @CreateDestroy ( )
1011class WorkerManager < W extends ModuleMethods >
1112 implements WorkerManagerInterface < W >
1213{
@@ -43,10 +44,8 @@ class WorkerManager<W extends ModuleMethods>
4344
4445 protected pool : Pool < ModuleThread < W > > ;
4546 protected logger : Logger ;
46- protected _running : boolean = false ;
47- protected _destroyed : boolean = false ;
4847
49- protected constructor ( {
48+ public constructor ( {
5049 workerFactory,
5150 cores,
5251 logger,
@@ -57,57 +56,35 @@ class WorkerManager<W extends ModuleMethods>
5756 } ) {
5857 this . logger = logger ;
5958 this . pool = Pool ( workerFactory , cores ) ;
60- this . _running = true ;
61- }
62-
63- get running ( ) : boolean {
64- return this . _running ;
65- }
66-
67- get destroyed ( ) : boolean {
68- return this . _destroyed ;
6959 }
7060
7161 public async destroy ( {
7262 force = false ,
7363 } : { force ?: boolean } = { } ) : Promise < void > {
74- if ( this . _destroyed ) {
75- return ;
76- }
7764 this . logger . info ( 'Destroying WorkerManager' ) ;
7865 await this . pool . terminate ( force ) ;
79- this . _running = false ;
80- this . _destroyed = true ;
8166 this . logger . info ( 'Destroyed WorkerManager' ) ;
8267 }
8368
69+ @ready ( new errors . ErrorWorkerManagerDestroyed ( ) )
8470 public async call < T > ( f : ( worker : ModuleThread < W > ) => Promise < T > ) : Promise < T > {
85- if ( ! this . _running ) {
86- throw new errors . ErrorWorkerManagerNotRunning ( ) ;
87- }
8871 return await this . pool . queue ( f ) ;
8972 }
9073
74+ @ready ( new errors . ErrorWorkerManagerDestroyed ( ) )
9175 public queue < T > (
9276 f : ( worker : ModuleThread < W > ) => Promise < T > ,
9377 ) : QueuedTask < ModuleThread < W > , T > {
94- if ( ! this . _running ) {
95- throw new errors . ErrorWorkerManagerNotRunning ( ) ;
96- }
9778 return this . pool . queue ( f ) ;
9879 }
9980
81+ @ready ( new errors . ErrorWorkerManagerDestroyed ( ) )
10082 public async completed ( ) : Promise < void > {
101- if ( ! this . _running ) {
102- throw new errors . ErrorWorkerManagerNotRunning ( ) ;
103- }
10483 return await this . pool . completed ( ) ;
10584 }
10685
86+ @ready ( new errors . ErrorWorkerManagerDestroyed ( ) )
10787 public async settled ( ) {
108- if ( ! this . _running ) {
109- throw new errors . ErrorWorkerManagerNotRunning ( ) ;
110- }
11188 return await this . pool . settled ( ) ;
11289 }
11390}
0 commit comments