无法从关闭的非缓冲通道读取

huangapple go评论100阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2022年4月2日 03:27:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/71711904.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定