[英]Populating an array using Channels in a WaitGroup routine
I want to populate an array of arrays inside a subroutine.我想在子例程中填充 arrays 数组。 I am trying to do this using a channel.
我正在尝试使用频道来做到这一点。 I am learning go, so unclear if this is the right way, so please correct me if I am going in the wrong direction, but my code never returns.
我正在学习 go,所以不清楚这是否是正确的方法,所以如果我走错了方向,请纠正我,但我的代码永远不会返回。 What am I doing wrong?
我究竟做错了什么?
var c = make(chan [15][4]string)
var mymap = map[int]string{
0: "www.foo.com",
1: "www.bar.com",
2: "www.baz.com",
3: "www.faz.com",
}
values := [3][4]string{{"A", "B", "C", "D"}}
var wg sync.WaitGroup
wg.Add(4) // one thread per index, total 4 indexes
for idx, url := range mymap {
go func(idx int, url string) {
defer wg.Done()
values[1][idx] = "someone"
values[2][idx] = "something"
c <- values
}(name, url)
}
wg.Wait()
close(c)
From code it looks like channel c is not read, and code is stuck there.从代码看来,通道 c 没有被读取,并且代码卡在那里。
This code doesn't need any synchronisation (channel etc.) because each goroutine is working on different part of values
, gr1->[xx,0], gr2->[xx,1], gr3-> [xx,2], gr4-> [xx,3].此代码不需要任何同步(通道等),因为每个 goroutine 都在处理不同部分的
values
,gr1->[xx,0]、gr2->[xx,1]、gr3-> [xx,2] , gr4-> [xx,3]。
Just remove the channel c from the code and this should work fine.只需从代码中删除通道 c ,这应该可以正常工作。
Change goroutine code to:将 goroutine 代码更改为:
go func(idx int, url string, arr *[3][4]string) {
defer wg.Done()
arr[1][idx] = "someone"
arr[2][idx] = "something"
}(idx, url, &values)
As previous answer states, you channel is not read.正如先前的答案所述,您的频道未被阅读。
However, if you buffer your channel (buffer of 4 in your case) the code should finish.但是,如果您缓冲您的频道(在您的情况下为 4 的缓冲区),则代码应该完成。
Also removing the channel is viable solution.删除通道也是可行的解决方案。 I am not sure why you pass the whole array you are building to the channel.
我不确定您为什么将要构建的整个数组传递给通道。 I assume you examining how the array gets changed and how the routines work.
我假设您正在检查数组是如何变化的以及例程是如何工作的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.