【发布时间】:2018-12-01 11:55:51
【问题描述】:
我有一个 sn-p 代码,我试图根据我如何放置 close 调用和位置来理解它
func main() {
ch := make(chan int, 2)
go func(ch chan int) {
for i := 1; i <= 5; i++ {
ch <- i
fmt.Println("Func goroutine sends data: ", i)
}
//Pos1 - Works perfectly
//close(ch)
}(ch)
fmt.Println("Main goroutine sleeps 2 seconds")
time.Sleep(time.Second * 2)
fmt.Println("Main goroutine begins receiving data")
//Pos2 - Puts in only 2 ints 1 and 2 and then prints only that
//close(ch)
for d := range ch {
fmt.Println("Main goroutine received data:", d)
}
//Pos3 - Throws fatal error
close(ch)
}
我一直在尝试理解和阅读这方面的博客,但仍然无法理解一些东西
- 当我在 Pos1 关闭时,它工作正常。但我不知道为什么
有用。缓冲区不能容纳超过 2 个元素在任何给定
时间,所以当写入 2 个元素时,循环将阻塞,直到
主路由进行读取。但我想在一个范围内做一个
缓冲通道,范围函数必须事先知道有多少
必须关闭该通道的迭代元素。为什么
close在这个职位上工作吗? - 当我把它作为位置 2 时,它只打印 2 个元素,这是有道理的,但为什么
for loop在尝试将更多元素写入关闭的通道时没有抛出异常? - 当我在 Pos3 关闭时,我得到一个异常
fatal error: all goroutines are asleep - deadlock!尽管所有 5 个整数都被打印出来。这是为什么呢?
【问题讨论】:
标签: go