例子1:
package main
import (
"fmt"
)
func main() {
ch1 := make(chan int, 1)
ch2 := make(chan int, 2)
select {
case <-ch1:
fmt.Println("ch1")
case <-ch2:
fmt.Println("ch2")
}
}
运行:
go run testSelect.go
结果:
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [select]:
main.main()
C:/Users/L/go/src/udpClient/select.go:10 +0x22d
很明显是死锁了,原因select一直在等待case而未结果
例子2:
package main
import (
"fmt"
"time"
)
func main() {
ch2 := make(chan bool, 1)
go func() {
time.Sleep(1e9) // sleep 1秒
ch2 <- true
}()
ch1 := make(chan int)
select {
case <-ch1:
case <-ch2:
fmt.Println("ch2!")
}
}
运行:
go run testSelect2.go
结果:
ch2!
运行到case2后会退出,不会一直阻塞等待