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

feat:add DoBefore #12

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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions workpool/workpool.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,21 @@ func (p *WorkPool) Do(fn TaskHandler) { // 添加到工作池,并立即返回
// p.task <- fn
}

// Do Add the task to the workpool and return immediately with a deadline, if the deadline is exceeded, the task will be aborted
func (p *WorkPool) DoBefore(fn TaskHandler, time time.Duration) {
ctx, cancel := context.WithTimeout(context.Background(), time)
p.Do(func() error {
select {
case <-ctx.Done():
cancel()
return ctx.Err()
default:
return fn()
}
},
)
}

// DoWait Add to the workpool and wait for execution to complete before returning
func (p *WorkPool) DoWait(task TaskHandler) { // 添加到工作池,并等待执行完成之后再返回
if p.IsClosed() { // closed
Expand Down
22 changes: 22 additions & 0 deletions workpool/workpool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ package workpool

import (
"fmt"
"sync/atomic"
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/xxjwxc/public/errors"
)

Expand Down Expand Up @@ -104,3 +106,23 @@ func TestWorkerPoolIsDone(t *testing.T) {
fmt.Println(wp.IsDone())
fmt.Println("down")
}

func TestDoBefore(t *testing.T) {
wp := New(1) // Set the maximum number of threads

var res int32 = 0

wp.Do(func() error {
time.Sleep(5 * time.Second)
atomic.AddInt32(&res, 1)
return nil
})

wp.DoBefore(func() error {
atomic.AddInt32(&res, 1)
return nil
}, 5*time.Second)

wp.Wait()
assert.Equal(t, int32(1), res)
}