问题1
问题:
代码:
package main
import (
"fmt"
)
func main() {
ch := make(chan int)
go func() {
for i:= 0; i<5;i++ {
fmt.Println("子go程, i=",i)
ch <- i // ch <- 0
}
}()
//time.Sleep(time.Second * 2) //子go程在主go程睡眠的2s内一直处于被阻塞状态
for i:= 0; i<5;i++ {
num := <- ch
fmt.Println("主go程读:", num)
}
}
执行结果:
GOROOT=D:\Go #gosetup
GOPATH=C:\GoProject #gosetup
D:\Go\bin\go.exe build -o C:\Users\think\AppData\Local\Temp\___go_build_02_channel_go.exe C:/GoProject/src/02-无缓冲channel.go #gosetup
C:\Users\think\AppData\Local\Temp\___go_build_02_channel_go.exe #gosetup
子go程, i= 0
子go程, i= 1
主go程读: 0
主go程读: 1
子go程, i= 2
子go程, i= 3
主go程读: 2
主go程读: 3
子go程, i= 4
主go程读: 4
Process finished with exit code 0