【发布时间】:2019-09-07 05:04:45
【问题描述】:
我有两组代码 - 读取包含随机文本行的文件,并将每一行加载到一个通道。我无法理解为什么返回错误。但另一个没有。案例 #1 返回“致命错误:所有 goroutine 都处于睡眠状态 - 死锁!”但案例 # 有效。
案例#1
func main() {
file, err := os.Open("/Users/sample/Downloads/wordlist")
if err != nil {
log.Fatal(err)
}
lines := make (chan string)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines <- scanner.Text()
}
close(lines)
for line := range (lines) {
fmt.Println(line)
}
}
案例#2
func main() {
file, err := os.Open("/Users/sample/Downloads/wordlist")
if err != nil {
log.Fatal(err)
}
lines := make (chan string)
go func() {
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines <- scanner.Text()
}
close(lines)
}()
for line := range (lines) {
fmt.Println(line)
}
}
【问题讨论】:
-
对无缓冲通道的通道操作会阻塞,直到发送方和接收方都准备好。案例#1 阻止发送到
lines,因为没有准备好的接收器。因为goroutine被阻塞了,所以代码不会在lines上执行receive。僵局。恐慌。繁荣! Go: fatal error: all goroutines are asleep - deadlock 的可能重复项。
标签: go