improve grpool to ensure atomicity for function Add

This commit is contained in:
John 2019-06-03 09:09:40 +08:00
parent 4f1047e853
commit 75dcc566b3
2 changed files with 29 additions and 4 deletions

View File

@ -59,10 +59,17 @@ func Jobs() int {
// The job will be executed asynchronously.
func (p *Pool) Add(f func()) {
p.list.PushFront(f)
// checking whether to create a new goroutine or not.
if p.count.Val() != p.limit {
p.fork()
// check whether to create a new goroutine or not.
if p.count.Val() == p.limit {
return
}
// ensure atomicity.
if p.limit != -1 && p.count.Add(1) > p.limit {
p.count.Add(-1)
return
}
// fork a new goroutine to consume the job list.
p.fork()
}
// Size returns current goroutine count of the pool.
@ -77,7 +84,6 @@ func (p *Pool) Jobs() int {
// fork creates a new goroutine pool.
func (p *Pool) fork() {
p.count.Add(1)
go func() {
defer p.count.Add(-1)
job := (interface{})(nil)

19
geg/os/grpool/grpool5.go Normal file
View File

@ -0,0 +1,19 @@
package main
import (
"fmt"
"github.com/gogf/gf/g/os/grpool"
"time"
)
func main() {
p := grpool.New(1)
for i := 0; i < 10; i++ {
v := i
p.Add(func() {
fmt.Println(v)
time.Sleep(3*time.Second)
})
}
time.Sleep(time.Minute)
}