当一个 channel 被关闭时,处于 sendq 中的 goroutine 会继续执行直到完成发送操作或者被其他因素阻塞。在完成发送操作后,它将从 sendq 中移除并继续执行后续的代码。如果一个 goroutine 在 sendq 中等待,但是 channel 已经关闭,它会收到一个零值(zero value)并且在继续执行前返回。\n\n下面是一个示例代码,演示了关闭 channel 后处于 sendq 中的 goroutine 的行为:\n\ngo\npackage main\n\nimport (\n\t"fmt"\n)\n\nfunc main() {\n\tch := make(chan int)\n\ngo func() {\n\tch <- 1\n\tch <- 2\n\tch <- 3\n}()\n\ngo func() {\n\tfor {\n\t val, ok := <-ch\n\t if !ok {\n\t // channel 已关闭\n\t fmt.Println("Channel closed")\n\t break\n\t }\n\t fmt.Println("Received:", val)\n\t}\n}()\n\n\t// 等待 goroutine 执行完毕\n\tfmt.Scanln()\n\tclose(ch)\n\tfmt.Scanln()\n}\n\n\n在上面的示例中,我们创建了一个 channel ch 并启动了两个 goroutine。第一个 goroutine 会向 channel 发送三个值 1、2、3。第二个 goroutine 会从 channel 接收值并打印出来。在主 goroutine 中,我们等待用户输入后关闭 channel。\n\n运行这段代码后,我们会看到第一个 goroutine 在执行发送操作时被阻塞,直到 channel 被关闭。一旦 channel 被关闭,第一个 goroutine 会继续执行并打印出 "Channel closed"。同时,第二个 goroutine 会接收到关闭的 channel,并在打印完最后一个值后退出。\n\n总结:在关闭 channel 后,处于 sendq 中的 goroutine 会继续执行直到完成发送操作或者被其他因素阻塞。

Golang 中关闭 Channel 后 Send Queue 中 Goroutine 的行为

原文地址: https://www.cveoy.top/t/topic/p7RY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录