go - 带通道的简单并行示例,导致死锁
问题描述
我正在尝试使用通道在 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
编辑:修复了关闭封闭频道的错误。
推荐阅读
- javascript - Atuo click 在附加的锚标签上不起作用
- pardot - Pardot 表单处理程序 - 垃圾邮件提交
- android - 为什么Android在更改区域设置时会更改县代码?
- php - 已读/未读新闻
- c# - 在 LINQ 中解构包含 ValueTuple 的容器
- function - Flutter Listview Builder 在单击图标上添加和删除更新数量文本字段
- javascript - webRTC:如何从被叫端更新视频流
- php - 用mysql分两行获取记录
- php - PHP - ZipArchive() 清理权限问题
- c# - 未在视图上显示的特定字段的模型状态错误验证