Skip to content

Commit 30bf38e

Browse files
committed
🐝 Performance improvement: use sync.Pool to cache active workers
1 parent 29f47ce commit 30bf38e

File tree

2 files changed

+10
-6
lines changed

2 files changed

+10
-6
lines changed

worker.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
package ants
2424

2525
import (
26+
"log"
2627
"time"
2728
)
2829

@@ -43,26 +44,27 @@ type Worker struct {
4344
// run starts a goroutine to repeat the process
4445
// that performs the function calls.
4546
func (w *Worker) run() {
47+
w.pool.incRunning()
4648
go func() {
4749
defer func() {
4850
if p := recover(); p != nil {
4951
w.pool.decRunning()
5052
if w.pool.PanicHandler != nil {
5153
w.pool.PanicHandler(p)
5254
} else {
53-
panic(p)
55+
log.Printf("worker exits from a panic: %v", p)
5456
}
5557
}
5658
}()
5759

5860
for f := range w.task {
5961
if f == nil {
6062
w.pool.decRunning()
61-
w.pool.cachePool.Put(w)
63+
w.pool.workerCache.Put(w)
6264
return
6365
}
6466
f()
65-
w.pool.putWorker(w)
67+
w.pool.revertWorker(w)
6668
}
6769
}()
6870
}

worker_func.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
package ants
2424

2525
import (
26+
"log"
2627
"time"
2728
)
2829

@@ -43,26 +44,27 @@ type WorkerWithFunc struct {
4344
// run starts a goroutine to repeat the process
4445
// that performs the function calls.
4546
func (w *WorkerWithFunc) run() {
47+
w.pool.incRunning()
4648
go func() {
4749
defer func() {
4850
if p := recover(); p != nil {
4951
w.pool.decRunning()
5052
if w.pool.PanicHandler != nil {
5153
w.pool.PanicHandler(p)
5254
} else {
53-
panic(p)
55+
log.Printf("worker exits from a panic: %v", p)
5456
}
5557
}
5658
}()
5759

5860
for args := range w.args {
5961
if args == nil {
6062
w.pool.decRunning()
61-
w.pool.cachePool.Put(w)
63+
w.pool.workerCache.Put(w)
6264
return
6365
}
6466
w.pool.poolFunc(args)
65-
w.pool.putWorker(w)
67+
w.pool.revertWorker(w)
6668
}
6769
}()
6870
}

0 commit comments

Comments
 (0)