發(fā)生死鎖的原因
- 主要是主協(xié)程因為channel而被阻塞,就會報dead lock隅忿。
往沒有make的channel里讀寫數(shù)據(jù),都會報錯
fatal error: all goroutines are asleep - deadlock! goroutine 1 [chan receive (nil chan)]:
主協(xié)程阻塞而報deadlock的例子:
package main
import (
"fmt"
)
func main() {
deadlockTest()
//time.Sleep(time.Second * 60)
}
func deadlockTest() {
fmt.Println("[deadlockTest] start")
ch := make(chan int)
results := make(chan int)
for i := 0; i < 2; i++ {
go func() {
// 把從channel里取得的數(shù)據(jù)挖息,再傳回去
x := <-ch
results <- x
}()
}
// 向輸入數(shù)據(jù)里傳兩個數(shù)據(jù)
ch <- 1
ch <- 2
for re := range results {
fmt.Printf("re:%v\n", re)
}
fmt.Println("[deadlockTest] end")
}
輸出:
dev@dev-VirtualBox test $ go run test_channel.go
[deadlockTest] start
re:1
re:2
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
main.deadlockTest()
/home/dev/test/test_channel.go:30 +0x1fc
main.main()
/home/dev/test/test_channel.go:8 +0x20
exit status 2
主協(xié)程使用range讀results信道卑雁,然后因為沒有把results關(guān)閉掉拓售,所以阻塞了】悖現(xiàn)在直接把deadlockTest方法go出去,就不會阻塞主協(xié)程了础淤,因而就不會報deadlock溪王。
package main
import (
"fmt"
"time"
)
func main() {
go deadlockTest()
time.Sleep(time.Second * 60)
}
func deadlockTest() {
fmt.Println("[deadlockTest] start")
ch := make(chan int)
results := make(chan int)
for i := 0; i < 2; i++ {
go func() {
// 把從channel里取得的數(shù)據(jù),再傳回去
x := <-ch
results <- x
}()
}
// 向輸入數(shù)據(jù)里傳兩個數(shù)據(jù)
ch <- 1
ch <- 2
for re := range results {
fmt.Printf("re:%v\n", re)
}
fmt.Println("[deadlockTest] end")
}
輸出:
dev@dev-VirtualBox test $ go run test_channel.go
[deadlockTest] start
re:1
re:2
dev@dev-VirtualBox test $