From 4138893096cb0f3b79488cbd2e4550a3c5fb66a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=81=93=E5=8F=8B=E8=AF=B7=E7=95=99=E6=AD=A5?= Date: Sun, 11 Dec 2022 14:30:33 +0800 Subject: [PATCH] Update README.md --- README.md | 68 +++++++++++++++++++++++++++---------------------------- 1 file changed, 34 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index 5fafa9e..4f17fd0 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,40 @@ GOPROXY=https://goproxy.cn go get -v github.com/lxzan/concurrency@latest #### Usage + +- WorkerGroup 工作组, 添加一组任务, 等待执行完成, 可以很好的替代`WaitGroup`. + +```go +package main + +import ( + "fmt" + "github.com/lxzan/concurrency" + "sync/atomic" +) + +func main() { + sum := int64(0) + w := concurrency.NewWorkerGroup() + for i := int64(1); i <= 10; i++ { + w.AddJob(concurrency.Job{ + Args: i, + Do: func(args interface{}) error { + fmt.Printf("%v ", args) + atomic.AddInt64(&sum, args.(int64)) + return nil + }, + }) + } + w.StartAndWait() + fmt.Printf("sum=%d\n", sum) +} +``` + +``` +4 5 6 7 8 9 10 1 3 2 sum=55 +``` + - WorkerQueue 工作队列, 可以不断往里面添加任务, 一旦有CPU资源空闲就去执行 ```go @@ -66,37 +100,3 @@ args=[1 3 5], ans=15 args=[1 3], ans=3 args=[1 3 5], ans=9 ``` - - -- WorkerGroup 工作组, 添加一组任务, 等待执行完成, 可以很好的替代`WaitGroup`. - -```go -package main - -import ( - "fmt" - "github.com/lxzan/concurrency" - "sync/atomic" -) - -func main() { - sum := int64(0) - w := concurrency.NewWorkerGroup() - for i := int64(1); i <= 10; i++ { - w.AddJob(concurrency.Job{ - Args: i, - Do: func(args interface{}) error { - fmt.Printf("%v ", args) - atomic.AddInt64(&sum, args.(int64)) - return nil - }, - }) - } - w.StartAndWait() - fmt.Printf("sum=%d\n", sum) -} -``` - -``` -4 5 6 7 8 9 10 1 3 2 sum=55 -```