From 75dcc566b3c5dbf83f623b6e1b8cf1490106a97e Mon Sep 17 00:00:00 2001 From: John Date: Mon, 3 Jun 2019 09:09:40 +0800 Subject: [PATCH] improve grpool to ensure atomicity for function Add --- g/os/grpool/grpool.go | 14 ++++++++++---- geg/os/grpool/grpool5.go | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) create mode 100644 geg/os/grpool/grpool5.go diff --git a/g/os/grpool/grpool.go b/g/os/grpool/grpool.go index 1de07ea32..8d2bf116c 100644 --- a/g/os/grpool/grpool.go +++ b/g/os/grpool/grpool.go @@ -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) diff --git a/geg/os/grpool/grpool5.go b/geg/os/grpool/grpool5.go new file mode 100644 index 000000000..3d12ee5db --- /dev/null +++ b/geg/os/grpool/grpool5.go @@ -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) +}