Skip to content

Commit f75a02d

Browse files
committed
优化锁粒度
1 parent b21cb09 commit f75a02d

2 files changed

Lines changed: 11 additions & 10 deletions

File tree

_examples/performance_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ func BenchmarkExecutor(b *testing.B) {
8484

8585
// go test -v -run=none -bench=^BenchmarkExecutorTime$ -benchmem -benchtime=1s
8686
func BenchmarkExecutorTime(b *testing.B) {
87-
executor := goes.NewExecutor(size)
87+
executor := goes.NewExecutor(workerNum)
8888

8989
num := uint32(0)
9090
task := func() {
@@ -104,7 +104,7 @@ func BenchmarkExecutorTime(b *testing.B) {
104104

105105
// // go test -v -run=none -bench=^BenchmarkAntsPool$ -benchmem -benchtime=1s
106106
// func BenchmarkAntsPool(b *testing.B) {
107-
// pool, _ := ants.NewPool(size)
107+
// pool, _ := ants.NewPool(workerNum)
108108
//
109109
// num := uint32(0)
110110
// task := func() {
@@ -123,7 +123,7 @@ func BenchmarkExecutorTime(b *testing.B) {
123123
//
124124
// // go test -v -run=none -bench=^BenchmarkAntsPoolTime$ -benchmem -benchtime=1s
125125
// func BenchmarkAntsPoolTime(b *testing.B) {
126-
// pool, _ := ants.NewPool(size)
126+
// pool, _ := ants.NewPool(workerNum)
127127
//
128128
// num := uint32(0)
129129
// task := func() {

executor.go

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -77,30 +77,31 @@ func (e *Executor) AvailableWorkers() int {
7777
// Submit submits a task to be handled by workers.
7878
func (e *Executor) Submit(task Task) error {
7979
e.lock.Lock()
80-
defer e.lock.Unlock()
8180

8281
if e.closed {
82+
e.lock.Unlock()
83+
8384
return ErrExecutorIsClosed
8485
}
8586

8687
worker := e.scheduler.Get()
8788
if worker == nil {
89+
e.lock.Unlock()
90+
8891
return ErrWorkerIsNil
8992
}
9093

91-
// We don't need to create a new worker if we got a worker with no tasks.
94+
// 1. We don't need to create a new worker if we got a worker with no tasks.
95+
// 2. The number of workers has reached the limit, so we can only use the worker we got.
9296
if worker.WaitingTasks() <= 0 || len(e.workers) >= e.conf.workerNum {
93-
worker.Accept(task)
94-
return nil
95-
}
97+
e.lock.Unlock()
9698

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 {
9999
worker.Accept(task)
100100
return nil
101101
}
102102

103103
worker = e.spawnWorker()
104+
e.lock.Unlock()
104105
worker.Accept(task)
105106
return nil
106107
}

0 commit comments

Comments
 (0)