很抱歉这个菜鸟问题,但我很难把头放在 go 的并发部分。基本上,下面的这个程序是我正在编写的一个更大的程序的简化版本,因此我想保持类似于下面的结构。
基本上,我想addCount(..)
使用无缓冲通道并发运行而不是等待 4 秒,并且当 中的所有元素int_slice
都被处理后,我想对它们进行另一个操作。然而,这个程序以“恐慌:关闭通道关闭”结束,如果我取消关闭通道,我会得到我期待的输出,但它会恐慌:“致命错误:所有 goroutines 都睡着了 - 死锁”
在这种情况下如何正确实现并发部分?
提前致谢!
package main
import (
"fmt"
"time"
)
func addCount(num int, counter chan<- int) {
time.Sleep(time.Second * 2)
counter <- num * 2
}
func main() {
counter := make(chan int)
int_slice := []int{2, 4}
for _, item := range int_slice {
go addCount(item, counter)
close(counter)
}
for item := range counter {
fmt.Println(item)
}
}
Run Code Online (Sandbox Code Playgroud)
以下是我在代码中发现的问题,下面是基于您的实现的工作版本。
如果 goroutine 尝试写入“无缓冲”通道,它将阻塞,直到有人从中读取为止。由于您在他们完成对频道的写入之前不会阅读,因此您会陷入僵局。
在它们被阻塞时关闭通道会打破死锁,但会出现错误,因为它们现在无法写入已关闭的通道。
解决方案包括:
创建一个缓冲通道,以便他们可以在不阻塞的情况下进行写入。
使用 async.WaitGroup
以便在关闭通道之前等待 goroutine 完成。
当一切都完成后,最后从通道读取。
看到这里,有评论:
package main
import (
"fmt"
"time"
"sync"
)
func addCount(num int, counter chan<- int, wg *sync.WaitGroup) {
// clear one from the sync group
defer wg.Done()
time.Sleep(time.Second * 2)
counter <- num * 2
}
func main() {
int_slice := []int{2, 4}
// make the slice buffered using the slice size, so that they can write without blocking
counter := make(chan int, len(int_slice))
var wg sync.WaitGroup
for _, item := range int_slice {
// add one to the sync group, to mark we should wait for one more
wg.Add(1)
go addCount(item, counter, &wg)
}
// wait for all goroutines to end
wg.Wait()
// close the channel so that we not longer expect writes to it
close(counter)
// read remaining values in the channel
for item := range counter {
fmt.Println(item)
}
}
Run Code Online (Sandbox Code Playgroud)