我对 golang 很陌生。
我的理解是,所有的go-routines都会同时执行。两个匿名 goroutines 将同时开始执行。但是当我运行这段代码时,它总是打印出来
a=1 first executed
a=1 second executed
panic: b != 1
不应该打印吗
a = 1
a = 1 first executed
Response true
and so on
或者
b =1
b = 1 first executed
Response true
and so on
既然向通道发送了一个值之后,相应的goroutine应该阻塞并等待接收者?
func main() {
var a, b int
var c = make(chan bool)
go func() {
b = 1
fmt.Println("b=1 first executed")
c <- true
fmt.Println("b=1 second executed")
if a != 1 { // impossible
panic("a != 1") // will never happen
}
fmt.Println("b=1 third executed")
}()
go func() {
a = 1
fmt.Println("a=1 first executed")
c <- true
fmt.Println("a=1 second executed")
if b != 1 { // impossible
panic("b != 1") // will never happen
}
fmt.Println("a=1 third executed")
}()
fmt.Println("Response ", <-c)
fmt.Println("Main executed")
}
慕沐林林
森林海
相关分类