如何解决带通道的简单并行示例,导致死锁
我正在尝试使用通道在 golang 中实现一个简单的并行化示例。代码试图实现一个并行化的映射函数。也使通道缓冲,以减轻对通道阻塞性质的限制。但代码仍然会导致死锁。
func pmmap(inp []int,f func(int) int,p int) {
var wg sync.WaitGroup
var output []chan int
tot := len(inp)
out := make(chan int,tot)
slice := tot / p
for i := 0; i < p; i++ {
temp := make(chan int,slice)
output = append(output,temp)
start_ind := slice * i
end_ind := start_ind + slice
fmt.Println(start_ind,end_ind)
wg.Add(1)
go func(si,ei int,out chan int,wg *sync.WaitGroup) {
fmt.Println("goroutine started with ",si,ei)
for ind := si; ind < ei; ind++ {
out <- f(inp[ind])
}
wg.Done()
}(start_ind,end_ind,output[i],&wg)
}
wg.Add(1)
go func(wg *sync.WaitGroup) {
for i := 0; i < p; i++ {
for val := range output[i] {
out <- val
}
close(output[i])
}
wg.Done()
}(&wg)
wg.Add(1)
go func(wg *sync.WaitGroup) {
for i := range out {
fmt.Println(i)
}
wg.Done()
}(&wg)
time.Sleep(time.Second * 6)
wg.Wait()
close(out)
}
func add4(i int) int {
return i + 4
}
func main() {
temp := []int{}
for i := 1; i <= 20; i++ {
temp = append(temp,i)
}
pmmap(temp,add4,2)
}
从上面代码的输出中,我得到死锁是因为永远不会读取通道输出[1]。但我不知道为什么
0 10
10 20
goroutine started with 0 10
goroutine started with 10 20
5
6
7
8
9
10
11
12
13
14
fatal error: all goroutines are asleep - deadlock!
解决方法
问题是频道上的 range
一直尝试从频道接收,直到频道关闭,但您在完成发送后没有 close
频道。
在代码中的 close(out)
之前添加 wg.Done
将修复它。
游乐场:https://play.golang.org/p/NbKTx6Lke7X
编辑:修复关闭频道的错误。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。