golang select的几种情况解析

func main() {
	msg := make(chan int)

	select {
	case <-msg:
		fmt.Println("msg")
	default:
		fmt.Println("default")
	}

	msg <- 1
	time.Sleep(time.Second * 1)
}

:default
    fatal error: all goroutines are asleep - deadlock!

func main() {
	msg := make(chan int)

	go func() {
		select {
		case <-msg:
			fmt.Println("msg")
		default:
			fmt.Println("default")
		}
	}()

	msg <- 1
	time.Sleep(time.Second * 1)
}

:msg

func main() {
	msg := make(chan int)

	go func() {
		select {
		case <-msg:
			fmt.Println("msg")
		default:
			fmt.Println("default")
		}
	}()

	time.Sleep(time.Second * 1)
	msg <- 1
	time.Sleep(time.Second * 1)
}

default
fatal error: all goroutines are asleep - deadlock!

猜你喜欢

转载自blog.csdn.net/coffiasd/article/details/114580900