goroutine并发执行多个任务并依次返回结果2——sync.WaitGroup

Golang
380
0
0
2022-04-11
标签   Golang进阶

直接上code

package main

import ("fmt""sync"
)

func func3(wg *sync.WaitGroup, ch chan string) {
    ch <- "func1 ok"
    wg.Done()
}

func func4(wg *sync.WaitGroup, ch chan string) {
    ch <- "func2 ok"
    wg.Done()
}

func SyncCron2(functions ...func(wg *sync.WaitGroup, ch chan string)) []string {
    chs := make([]chan string, len(functions))

    // 关闭 chan 
    defer func() {for _, c := range chs {if c != nil {close(c)}}}()

    wg := sync.WaitGroup{}
    wg.Add(len(functions))

    for i, f := range functions {
        chs[i] = make(chan string, 1)
        go f(&wg, chs[i])}

    wg.Wait()

    result := make([]string, len(functions))for i, ch := range chs {
        result[i] = <-ch
    }

    return result
}

func main() {
    r := SyncCron2(func3, func4)
    fmt.Println(r)
}

小细节:

goroutine并发执行多个任务并依次返回结果2——sync.WaitGroup

这里如果不使用缓冲通道会报下面的错误:

all goroutines are asleep - deadlock!

详细原理可参考 该文章