A record of all goroutines are asleep

func testDeadLock(c chan int) {
	for {
		fmt.Println(<-c)
	}
}

func main() {
	c := make(chan int)
	c <- 'A'
	go testDeadLock(c)
	time.Sleep(time.Millisecond)
}

The above code will generate fatal error: all goroutines are asleep - deadlock! error message

func testDeadLock(c chan int) {
	for {
		fmt.Println(<-c)
	}
}

func main() {
	c := make(chan int)
	go testDeadLock(c)
	c <- 'A'
	time.Sleep(time.Millisecond)
}

And this code will normally output 65. The reason for the above difference is that we declared an unbuffered channel, so when writing to this channel, it will be blocked until a certain coroutine reads this channel, but we The program is blocked when it is written and will not execute the following read operation, so the program is deadlocked.

Guess you like

Origin blog.csdn.net/coffiasd/article/details/114265155