直接上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)
}
小細節:
這裡如果不使用緩衝通道會報下面的錯誤:all goroutines are asleep - deadlock!
詳細原理可參考 該文章
本作品採用《CC 協議》,轉載必須註明作者和本文連結