🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] > https://github.com/sourcegraph/conc ## WaitGroup std ``` var wg sync.WaitGroup wg.Add(1) go func() { wg.Done() fmt.Printf("%+v\n", "hello") }() fmt.Printf("%+v\n", "1") wg.Wait() ``` conc ``` var wg conc.WaitGroup defer wg.Wait() wg.Go(func() { fmt.Printf("%+v\n", "asd") }) fmt.Printf("%+v\n", "asdasd") ``` ## 处理error std ``` type caughtPanicError struct { val any stack []byte } func (e *caughtPanicError) Error() string { return fmt.Sprintf( "panic: %q\n%s", e.val, string(e.stack) ) } func main() { done := make(chan error) go func() { defer func() { if v := recover(); v != nil { done <- &caughtPanicError{ val: v, stack: debug.Stack() } } else { done <- nil } }() doSomethingThatMightPanic() }() err := <-done if err != nil { panic(err) } } ``` conc ``` func main() { var wg conc.WaitGroup wg.Go(doSomethingThatMightPanic) // panics with a nice stacktrace wg.Wait() } ``` ## 并发处理 std ``` func main() { var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func() { defer wg.Done() // crashes on panic! doSomething() }() } wg.Wait() } ``` conc ``` func main() { var wg conc.WaitGroup for i := 0; i < 10; i++ { wg.Go(doSomething) } wg.Wait() } ``` ## 限制并发大小 std ``` func process(stream chan int) { var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func() { defer wg.Done() for elem := range stream { handle(elem) } }() } wg.Wait() } ``` conc ``` func process(stream chan int) { p := pool.New().WithMaxGoroutines(10) for elem := range stream { elem := elem p.Go(func() { handle(elem) }) } p.Wait() } ``` ## 并发迭代 std ``` func process(values []int) { feeder := make(chan int, 8) var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func() { defer wg.Done() for elem := range feeder { handle(elem) } }() } for _, value := range values { feeder <- value } close(feeder) wg.Wait() } ``` conc ``` func process(values []int) { iter.ForEach(values, handle) } ``` ## 并发map conc ``` input := []string{"1", "2", "3"} i := iter.Map[string, string](input, func(t *string) string { *t = *t + "hello" return *t }) fmt.Printf("%+v\n", i) // [1hello 2hello 3hello] ``` ## map stream conc ``` func mapStream(in chan int, out chan int, f func(int) int) { s := stream.New().WithMaxGoroutines(10) for elem := range in { elem := elem s.Go(func() stream.Callback { res := f(elem) return func() { out <- res } }) } s.Wait() } ```