Skip to content

Commit 273bd3f

Browse files
committed
Optimize the completion signal
- Using an empty struct instead of a boolean flag. Takes zero memory and makes the code more elegant. - Also removes the need to check for the value passed as we are only concerned about receiving the value.
1 parent 3d8061b commit 273bd3f

File tree

1 file changed

+16
-20
lines changed

1 file changed

+16
-20
lines changed

grpool.go

Lines changed: 16 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import "sync"
66
type worker struct {
77
workerPool chan *worker
88
jobChannel chan Job
9-
stop chan bool
9+
stop chan struct{}
1010
}
1111

1212
func (w *worker) start() {
@@ -19,11 +19,9 @@ func (w *worker) start() {
1919
select {
2020
case job = <-w.jobChannel:
2121
job()
22-
case stop := <-w.stop:
23-
if stop {
24-
w.stop <- true
25-
return
26-
}
22+
case <-w.stop:
23+
w.stop <- struct{}{}
24+
return
2725
}
2826
}
2927
}()
@@ -33,15 +31,15 @@ func newWorker(pool chan *worker) *worker {
3331
return &worker{
3432
workerPool: pool,
3533
jobChannel: make(chan Job),
36-
stop: make(chan bool),
34+
stop: make(chan struct{}),
3735
}
3836
}
3937

4038
// Accepts jobs from clients, and waits for first free worker to deliver job
4139
type dispatcher struct {
4240
workerPool chan *worker
4341
jobQueue chan Job
44-
stop chan bool
42+
stop chan struct{}
4543
}
4644

4745
func (d *dispatcher) dispatch() {
@@ -50,18 +48,16 @@ func (d *dispatcher) dispatch() {
5048
case job := <-d.jobQueue:
5149
worker := <-d.workerPool
5250
worker.jobChannel <- job
53-
case stop := <-d.stop:
54-
if stop {
55-
for i := 0; i < cap(d.workerPool); i++ {
56-
worker := <-d.workerPool
57-
58-
worker.stop <- true
59-
<-worker.stop
60-
}
51+
case <-d.stop:
52+
for i := 0; i < cap(d.workerPool); i++ {
53+
worker := <-d.workerPool
6154

62-
d.stop <- true
63-
return
55+
worker.stop <- struct{}{}
56+
<-worker.stop
6457
}
58+
59+
d.stop <- struct{}{}
60+
return
6561
}
6662
}
6763
}
@@ -70,7 +66,7 @@ func newDispatcher(workerPool chan *worker, jobQueue chan Job) *dispatcher {
7066
d := &dispatcher{
7167
workerPool: workerPool,
7268
jobQueue: jobQueue,
73-
stop: make(chan bool),
69+
stop: make(chan struct{}),
7470
}
7571

7672
for i := 0; i < cap(d.workerPool); i++ {
@@ -129,6 +125,6 @@ func (p *Pool) WaitAll() {
129125

130126
// Will release resources used by pool
131127
func (p *Pool) Release() {
132-
p.dispatcher.stop <- true
128+
p.dispatcher.stop <- struct{}{}
133129
<-p.dispatcher.stop
134130
}

0 commit comments

Comments
 (0)