料青山看我应如是
如果您按照顺序执行的方式重写代码,那么发生的事情就会变得更加清晰。原始代码:func main() { a := make(chan bool) b := make(chan int64) go func(a chan bool, b chan int64) { fmt.Println("Here1") a <- true b <- 12 } (a,b) fmt.Println("Here2") fmt.Println(fmt.Sprintf("%d", <-b)) fmt.Println(fmt.Sprintf("%v", <-a))}相同代码顺序执行的紧密表示: a := make(chan bool) b := make(chan int64) fmt.Println("Here2") // Prints // Pass control to new goroutine fmt.Println("Here1") a <- true // Write to channel a and block goroutine here and pass control to main fmt.Println(fmt.Sprintf("%d", <-b)) // Tries to read from b but nothing has been written to it so blocks. At this point all your goroutines are blocked hence the deadlock. fmt.Println(fmt.Sprintf("%v", <-a)) // doesn't even reach here. b <- 12}