我正在尝试使用通道在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 1010 20goroutine started with 0 10goroutine started with 10 20567891011121314fatal error: all goroutines are asleep - deadlock!
1 回答
胡说叔叔
TA贡献1804条经验 获得超8个赞
问题在于,在通道关闭之前,通过通道不断尝试从通道接收,但在完成发送后您没有通道。range
close
在代码中添加之前将修复它。close(out)
wg.Done
游乐场: https://play.golang.org/p/NbKTx6Lke7X
编辑:修复了关闭已关闭频道的错误。
- 1 回答
- 0 关注
- 100 浏览
添加回答
举报
0/150
提交
取消