Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a new method -- ReleaseWaitAllWorkersExit() for waiting all worke… #245

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions ants.go
Expand Up @@ -124,6 +124,11 @@ func Release() {
defaultAntsPool.Release()
}

// ReleaseWaitAllWorkersExit Closes the default pool and wait all workers exit.
func ReleaseWaitAllWorkersExit() {
defaultAntsPool.ReleaseWaitAllWorkersExit()
}

// Reboot reboots the default pool.
func Reboot() {
defaultAntsPool.Reboot()
Expand Down
25 changes: 25 additions & 0 deletions ants_test.go
Expand Up @@ -846,3 +846,28 @@ func TestReleaseTimeout(t *testing.T) {
err = pf.ReleaseTimeout(2 * time.Second)
assert.NoError(t, err)
}

func TestReleaseWaitAllWorkersExit(t *testing.T) {
p, _ := NewPool(10)
for i := 0; i < 5; i++ {
_ = p.Submit(func() {
time.Sleep(time.Second)
})
}
assert.NotZero(t, p.Running())
p.ReleaseWaitAllWorkersExit()
assert.Zero(t, p.running)
}

func TestReleaseWaitAllWorkersExitDefaultPool(t *testing.T) {

beforeGoNum := runtime.NumGoroutine()
defaultAntsPool, _ = NewPool(DefaultAntsPoolSize)
afterGoNum := runtime.NumGoroutine()
assert.Equal(t, beforeGoNum+1, afterGoNum)

ReleaseWaitAllWorkersExit()
endGoNum := runtime.NumGoroutine()
assert.Equal(t, beforeGoNum, endGoNum)

}
18 changes: 18 additions & 0 deletions pool.go
Expand Up @@ -253,6 +253,24 @@ func (p *Pool) ReleaseTimeout(timeout time.Duration) error {
return ErrTimeout
}

// ReleaseWaitAllWorkersExit is like Release, but it will wait all workers to exit.
func (p *Pool) ReleaseWaitAllWorkersExit() {
if p.IsClosed() || p.stopHeartbeat == nil {
return
}

p.stopHeartbeat()
p.stopHeartbeat = nil
p.Release()

for {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里有一个风险,如果某一个 worker 里的任务阻塞了,则这里就永远无法退出了。

Copy link
Owner

@panjf2000 panjf2000 Aug 8, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

另外,其实你这里的代码和 ReleaseTimeout(timeout) 基本是一样的,我更倾向于直接修改 ReleaseTimeout(timeout),当 timeout < 0 的时候,就一直等到所有 workers 退出才结束,这样也不用新加一个 API 了。

if p.Running() == 0 && atomic.LoadInt32(&p.heartbeatDone) == 1 {
return
}
time.Sleep(10 * time.Millisecond)
}
}

// Reboot reboots a closed pool.
func (p *Pool) Reboot() {
if atomic.CompareAndSwapInt32(&p.state, CLOSED, OPENED) {
Expand Down