英文:
Unable to read from close unbuffered channel
问题
我知道我们可以从缓冲关闭的通道中读取数据。所以,我非常有信心我们也可以从非缓冲通道中读取数据。然而,我无法进行测试。
根据我所知,在这段代码中,首先应该执行c<-5
,然后才会由test
协程关闭通道。然而,事实并非如此。有人可以告诉我为什么在这里"协作调度"不起作用吗?为什么test
协程先执行?
英文:
I know we can read from buffered close channels. So, I feel very confident that we can do from unbuffered as well. However, I am not able to test it out.
func test(c chan int) {
time.Sleep(10 * time.Millisecond)
close(c)
fmt.Println(<-c)
}
func main() {
c := make(chan int)
go test(c)
c <- 5
}
Output
panic: send on closed channel
goroutine 1 [running]:
main.main()
/Users/tanmay.jhazomato.com/Projects/search-service/practice.go:17 +0x85
Process finished with the exit code 2
As far as I know, in this code. First c<-5
should be executed before channel getting closed by test go routine
. However, that's not the case. Can somebody tell me when cooperative scheduling
is not working here? Why is it that the test go routine
is executing first?
答案1
得分: 1
一个发送到无缓冲通道的操作会阻塞,直到另一个 goroutine 从中读取。因此,在主 goroutine 等待向通道写入时,第二个 goroutine 关闭了它,导致程序在关闭的通道上进行发送操作时失败。
英文:
A send to an unbuffered channel will block until another goroutine reads from it. So, while the main goroutine is waiting to write to the channel, the second goroutine closes it, and the program fails with a send on the closed channel.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论