慕田峪7331174
2023-07-04 19:05:56
我在 Golang 教程中學(xué)習(xí) Go select 語(yǔ)句時(shí)嘗試對(duì)代碼進(jìn)行一些更改: https: //tour.golang.org/concurrency/5。但是,我遇到了問(wèn)題: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這是我嘗試并遇到問(wèn)題的代碼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)}起初,我認(rèn)為結(jié)果將與下面代碼的結(jié)果相同//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您能解釋一下執(zhí)行第一個(gè)示例時(shí)死鎖的根本原因是什么嗎?在go例程中發(fā)送值退出通道與在主線程中發(fā)送值退出通道有什么區(qū)別?感謝你們。
1 回答

寶慕林4294392
TA貢獻(xiàn)2021條經(jīng)驗(yàn) 獲得超8個(gè)贊
該quit通道是無(wú)緩沖通道。在發(fā)送和接收 goroutine 都準(zhǔn)備好之前,無(wú)緩沖通道上的通信不會(huì)繼續(xù)。該語(yǔ)句quit <- 0在應(yīng)用程序執(zhí)行函數(shù)以接收值之前阻塞。接收 Goroutine 永遠(yuǎn)不會(huì)準(zhǔn)備好
通過(guò)關(guān)閉通道修復(fù):
c := make(chan int)
quit := make(chan int)
go func() {
fmt.Println(<-c)
}()
close(quit)
fibonacci(c, quit)
...或者通過(guò)緩沖通道
c := make(chan int, 1) // <- note size 1
quit := make(chan int)
go func() {
fmt.Println(<-c)
}()
quit <- 0
fibonacci(c, quit)
在這種情況下,fibonacci將在產(chǎn)生值之前退出。
- 1 回答
- 0 關(guān)注
- 139 瀏覽
添加回答
舉報(bào)
0/150
提交
取消