我在 Golang 教程中學習 Go select 語句時嘗試對代碼進行一些更改: https: //tour.golang.org/concurrency/5。但是,我遇到了問題:fatal error: all goroutines are asleep - deadlock!goroutine 1 [chan send]:main.main() concurrency.go:26 +0xa3goroutine 33 [chan receive]:main.main.func1(0xc000088000) concurrency.go:24 +0x42created by main.main concurrency.go:23 +0x89exit status 2這是我嘗試并遇到問題的代碼func fibonacci(c, quit chan int) { x, y := 0, 1 for { select { case c <- x: //sending value x into channel c x, y = y, x+y case <-quit: //receive value from quit fmt.Println("quit") return } }}func main() { //create two channels c := make(chan int) quit := make(chan int) go func() { //spin off the second function in order to let consume from c , so fibonaci can continue to work fmt.Println(<-c) //read value from channel c }() //Try moving the statement that send value to channel quit in order to //return function fibonacci quit <- 0 fibonacci(c, quit)}起初,我認為結果將與下面代碼的結果相同//function fibonacci is same with the first onefunc fibonacci(c, quit chan int) { x, y := 0, 1 for { select { case c <- x: //sending value x into channel c x, y = y, x+y case <-quit: //receive value from quit fmt.Println("quit") return } }}func main() { //create two channels c := make(chan int) quit := make(chan int) go func() { //spin off the second function in order to let consume from c , so fibonaci can continue to work fmt.Println(<-c) //read value from channel c quit <- 0 //CHANGE: move the statement inside the closure function }() fibonacci(c, quit)}輸出是0quit您能解釋一下執行第一個示例時死鎖的根本原因是什么嗎?在go例程中發送值退出通道與在主線程中發送值退出通道有什么區別?感謝你們。
當向 Go 例程之外的通道發送值時,Go 例程會出現死鎖
慕田峪7331174
2023-07-04 19:05:56