代码如下:
func makeData() map[string][]Data {
m := make(map[string][]Data)
s := "abcdefghijklmno"
for i, c := range s {
data := []Data{
{value: "hey_" + string(c), id: i * i},
{value: "hello_" + string(c) + string(c), id: i + i},
{value: "bye_" + string(c), id: i + 1},
}
m[strconv.Itoa(i)] = data
}
return m
}
func process(key string, value []Data) (*Result, error) {
if key == "hey_a" {
return nil, errors.New("error")
}
res := Result{data: Data{value: "hi", id: 0}, id: 1}
return &res, nil
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
m := makeData()
errg := new(errgroup.Group)
mapChan := make(chan StringAndData)
sliceChan := make(chan *Result)
for key, value := range m {
key := key
value := value
errg.Go(func() error {
return func(key string, value []Data) error {
res, err := process(key, value)
if err != nil {
return err
}
if res == nil {
return nil
}
if res.data.id == 1 {
mapChan <- StringAndData{
str: key,
data: res.data,
}
return nil
}
sliceChan <- res
return nil
}(key, value)
})
}
if err := errg.Wait(); err != nil {
fmt.Println("error")
} else {
fmt.Println("success")
}
close(mapChan)
close(sliceChan)
for ac := range mapChan {
fmt.Println(ac.str)
}
}
type Data struct {
value string
id int
}
type Result struct {
data Data
id int
}
type StringAndData struct {
str string
data Data
}
操场
我得到了,但我正在关闭频道之后,我无法理解原因。fatal error: all goroutines are asleep - deadlock!errg.Wait()
我正在尝试打印使用 关闭通道后从通道获得的值。range
我是 Go 的渠道和并发新手,非常感谢任何帮助!
编辑添加了游乐场链接中的所有代码
蝴蝶刀刀
相关分类