const Max = 10000000 type GoroutinePoll struct { Queue chan func() error Total, Num int Result chan error FinishCallBack func() error } func (g *GoroutinePoll) Init(total int) { g.Total = total g.Queue = make(chan func() error, total) g.Result = make(chan error, total) } func (g *GoroutinePoll) SetFinishCallBack(f func() error) { g.FinishCallBack = f } func (g *GoroutinePoll) Add(f func() error) error { if len(g.Queue) == g.Total || g.Total == 0 { return errors.New(" add goroutine fail!") } g.Queue <- f g.Num++ return nil } func (g *GoroutinePoll) Start() { for i := 0; i < g.Num; i++ { v, ok := <-g.Queue if !ok { break } go func() { err := v() g.Result <- err }() } for i := 0; i < g.Num; i++ { err, ok := <-g.Result if !ok { break } if err != nil { fmt.Println(err) } } if err := g.FinishCallBack(); err != nil { fmt.Println("执行回调函数失败!", err) } } func (g *GoroutinePoll) Close() { close(g.Queue) close(g.Result) } func main() { runtime.GOMAXPROCS(16) total := 10 g := GoroutinePoll{} g.Init(total) finshCallBack := func() error { fmt.Println("callback !") return nil } g.SetFinishCallBack(finshCallBack) f1 := func() error { for i := 0; i < Max; i++ { } return nil } g.Add(f1) f2 := func() error { for i := 0; i < Max; i++ { } return nil } g.Add(f2) f3 := func() error { for i := 0; i < Max; i++ { } return nil } g.Add(f3) f4 := func() error { for i := 0; i < Max; i++ { } return nil } g.Add(f4) now := time.Now() g.Start() g.Close() fmt.Println(time.Since(now)) now = time.Now() f1() f2() f3() f4() fmt.Println(time.Since(now)) }
callback !
3.863554ms
12.890933ms
有疑问加站长微信联系(非本文作者)