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

Submit a task with args to pool #158

Open
wants to merge 4 commits 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
3 changes: 2 additions & 1 deletion README.md
Expand Up @@ -226,9 +226,10 @@ p, _ := ants.NewPool(10000)
```

### Submit tasks
Tasks can be submitted by calling `ants.Submit(func())`
Tasks can be submitted by calling `ants.Submit(func())` or `ants.SubmitWithArgs(func(args...))`
```go
ants.Submit(func(){})
ants.SubmitWithArgs(func(args...))
```

### Tune pool capacity in runtime
Expand Down
25 changes: 25 additions & 0 deletions ants_test.go
Expand Up @@ -669,3 +669,28 @@ func TestRestCodeCoverage(t *testing.T) {
t.Logf("pre-malloc pool with func, after tuning capacity, capacity:%d, running:%d", ppremWithFunc.Cap(),
ppremWithFunc.Running())
}

func TestPool_SubmitWithArgs(t *testing.T) {
var wg sync.WaitGroup
p, _ := NewPool(AntsSize)
defer p.Release()

var syncSum, asyncSum int
var mux sync.Mutex
for i := 0; i < Param; i++ {
syncSum += i
wg.Add(1)

_ = p.SubmitWithArgs(func(args ...interface{}) {
mux.Lock()
defer mux.Unlock()
asyncSum += args[0].(int)
wg.Done()
},
i)
}
wg.Wait()
if syncSum != asyncSum {
t.Fatalf("sum mismatch: %d != %d", syncSum, asyncSum)
}
}
10 changes: 10 additions & 0 deletions pool.go
Expand Up @@ -154,6 +154,16 @@ func (p *Pool) Submit(task func()) error {
return nil
}

// SubmitWithArgs submits a task with arguments to this pool.
func (p *Pool) SubmitWithArgs(task func(args ...interface{}), args ...interface{}) error {
f := func(args ...interface{}) func() {
return func() {
task(args...)
}
}
return p.Submit(f(args...))
}

// Running returns the number of the currently running goroutines.
func (p *Pool) Running() int {
return int(atomic.LoadInt32(&p.running))
Expand Down