@@ -45,23 +45,27 @@ func NewExecutor(workerNum int, opts ...Option) *Executor {
4545 panic ("goes: worker's queue size <= 0" )
4646 }
4747
48- executor := & Executor {
49- conf : conf ,
50- closed : false ,
51- lock : conf .newLocker (),
52- }
53-
5448 workers := make ([]* worker , 0 , conf .workerNum )
55- for range conf .workerNum {
56- worker := newWorker (executor )
57- workers = append (workers , worker )
49+ executor := & Executor {
50+ conf : conf ,
51+ workers : workers ,
52+ scheduler : conf .newScheduler (),
53+ closed : false ,
54+ lock : conf .newLocker (),
5855 }
5956
60- executor .workers = workers
61- executor .scheduler = conf .newScheduler (workers )
57+ executor .spawnWorker ()
6258 return executor
6359}
6460
61+ func (e * Executor ) spawnWorker () * worker {
62+ worker := newWorker (e )
63+
64+ e .workers = append (e .workers , worker )
65+ e .scheduler .Set (e .workers )
66+ return worker
67+ }
68+
6569// AvailableWorkers returns the number of workers available in the executor.
6670func (e * Executor ) AvailableWorkers () int {
6771 e .lock .Lock ()
@@ -84,6 +88,19 @@ func (e *Executor) Submit(task Task) error {
8488 return ErrWorkerIsNil
8589 }
8690
91+ // We don't need to create a new worker if we got a worker with no tasks.
92+ if worker .WaitingTasks () <= 0 || len (e .workers ) >= e .conf .workerNum {
93+ worker .Accept (task )
94+ return nil
95+ }
96+
97+ // The number of workers has reached the limit, so we can only use the worker we got.
98+ if len (e .workers ) >= e .conf .workerNum {
99+ worker .Accept (task )
100+ return nil
101+ }
102+
103+ worker = e .spawnWorker ()
87104 worker .Accept (task )
88105 return nil
89106}
0 commit comments