mirror of
https://gitee.com/johng/gf.git
synced 2024-11-30 19:27:46 +08:00
improve grpool to ensure atomicity for function Add
This commit is contained in:
parent
4f1047e853
commit
75dcc566b3
@ -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
19
geg/os/grpool/grpool5.go
Normal 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)
|
||||
}
|
Loading…
Reference in New Issue
Block a user