我在并发和缓冲的通道上玩耍,遇到了以下使我感到困惑的问题: https://play.golang.org/p/wir7wP2u-yf
为什么函数echo中的(大小为3的)信道的“卸载”确实发生在包含4的情况下?
为什么在将5发送到信道后,信道c的容量仍保持为0?
为什么不回声10个?
package main
import "fmt"
func echo(c chan int) {
for num := range c {
//fmt.Printf("length of channel c: %v\n",len(c))
fmt.Println(num)
}
fmt.Println("Done iterating")
}
func main() {
fmt.Println("main() started")
c := make(chan int, 3)
go echo(c)
c <- 1
fmt.Printf("After 1, capacity %v\n",len(c))
c <- 2
fmt.Printf("After 2, capacity %v\n",len(c))
c <- 3
fmt.Printf("After 3, capacity %v\n",len(c))
c <- 4 // blocks here
fmt.Printf("After 4, capacity %v\n",len(c))
c <- 5
fmt.Printf("After 5, capacity %v\n",len(c))
c <- 6
fmt.Printf("After 6, capacity %v\n",len(c))
c <- 7
fmt.Printf("After 7, capacity %v\n",len(c))
c <- 8
fmt.Printf("After 8, capacity %v\n",len(c))
c <- 9
fmt.Printf("After 9, capacity %v\n",len(c))
c <- 10
fmt.Printf("After 10\n")
fmt.Println("main() stopped")
}
答案 0 :(得分:-1)
这完全取决于操作系统调度。上面的代码的结果并不总是相同的。
main() started
After 1, capacity 1
After 2, capacity 2
After 3, capacity 3
1
2
3
4
After 4, capacity 0
After 5, capacity 0
After 6, capacity 1
After 7, capacity 2
After 8, capacity 3
5
6
7
8
9
After 9, capacity 0
After 10
main() stopped
此结果可能与您在操场上看到的结果相同。但是,这是不可预测的,因为我们无法确定操作系统如何安排goroutine的执行顺序。
如果我在本地计算机上运行此代码,则每次执行它都会有所不同。见下文:
首次运行
main() started
After 1, capacity 1
After 2, capacity 1
After 3, capacity 2
1
2
3
4
After 4, capacity 3
After 5, capacity 0
5
After 6, capacity 0
After 7, capacity 1
After 8, capacity 2
After 9, capacity 3
6
7
8
9
10
After 10
main() stopped
第二次运行
main() started
After 1, capacity 1
After 2, capacity 2
1
2
3
After 3, capacity 2
After 4, capacity 0
4
5
After 5, capacity 1
After 6, capacity 0
After 7, capacity 1
After 8, capacity 2
6
7
8
9
After 9, capacity 3
After 10
main() stopped
10
因此,您的问题的答案将是
接收通道(用于4)刚在主功能中的fmt.Printf
之前执行。每次执行可能会有所不同。在本地计算机上尝试。
类似于1。它只是在range
之前被len(c)
读取。
主要goroutine在从通道读取10之前退出。在这种情况下,您应该等待使用某种技术读取频道中的所有项目,例如睡眠时间,等待同步包组或其他频道。
您可以通过在要检查的行之间插入time.Sleep(time.Second)
来查看该程序的工作方式。
例如,如果您在fmt.Println("main() stopped")
之前睡了1秒钟,则总是可以看到10
回显,因为主goroutine将等待一秒钟。 (1秒足以读取频道中的内容)
package main
import "fmt"
import "time"
func echo(c chan int) {
for num := range c {
fmt.Println(num)
}
fmt.Println("Done iterating")
}
func main() {
fmt.Println("main() started")
c := make(chan int, 3)
go echo(c)
c <- 1
fmt.Printf("After 1, capacity %v\n",len(c))
c <- 2
fmt.Printf("After 2, capacity %v\n",len(c))
c <- 3
fmt.Printf("After 3, capacity %v\n",len(c))
c <- 4 // blocks here
fmt.Printf("After 4, capacity %v\n",len(c))
c <- 5
fmt.Printf("After 5, capacity %v\n",len(c))
c <- 6
fmt.Printf("After 6, capacity %v\n",len(c))
c <- 7
fmt.Printf("After 7, capacity %v\n",len(c))
c <- 8
fmt.Printf("After 8, capacity %v\n",len(c))
c <- 9
fmt.Printf("After 9, capacity %v\n",len(c))
c <- 10
fmt.Printf("After 10\n")
time.Sleep(time.Second)
fmt.Println("main() stopped")
}