Skip to content

Commit

Permalink
handle idle recycle duration is 0
Browse files Browse the repository at this point in the history
  • Loading branch information
tiancaiamao committed Dec 30, 2022
1 parent 9170883 commit 4025bc8
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 2 deletions.
23 changes: 21 additions & 2 deletions gp.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,30 @@ func worker(p *Pool, fn func()) {
default:
return
}
defer func() { <-p.count }()

// Enter the worker loop.
done := false
if p.idleRecycle == 0 {
workerLoopSimple(p)
} else {
workerLoop(p)
}
}

func workerLoopSimple(p *Pool) {
for {
select {
case f := <-p.ch:
f()
case <-p.closed:
return
}
}
}

func workerLoop(p *Pool) {
t := time.NewTimer(p.idleRecycle)
done := false
for !done {
select {
case f := <-p.ch:
Expand All @@ -60,7 +80,6 @@ func worker(p *Pool, fn func()) {
done = true
}
}
<-p.count
}

// Close releases the goroutines in the Pool.
Expand Down
44 changes: 44 additions & 0 deletions gp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,47 @@ func TestT(t *testing.T) {
t.Fail()
}
}

func TestPanic(t *testing.T) {
pool := New(2, 0)
// Fill the pool
for i:=0; i<10; i++ {
pool.Go(func() {})
}
time.Sleep(100*time.Millisecond)
for i := 0; i < 100; i++ {
pool.Go(func() {
defer func() {
if r := recover(); r != nil {
}
}()
panic(1)
})
}
time.Sleep(100*time.Millisecond)
if len(pool.count) != 2 {
t.Fail()
}
}

func TestIdleRecycle(t *testing.T) {
pool := New(10, 100*time.Millisecond)
for i:=0; i<1000; i++ {
pool.Go(func(){})
}
time.Sleep(300*time.Millisecond)
if len(pool.count) != 0 {
t.Fail()
}
pool.Close()

pool = New(10, 0)
for i:=0; i<1000; i++ {
pool.Go(func(){})
}
time.Sleep(300*time.Millisecond)
if len(pool.count) == 0 {
t.Fail()
}
pool.Close()
}

0 comments on commit 4025bc8

Please sign in to comment.