死鎖:
1岭参、單goroutine自己死鎖
channel應(yīng)該至少在兩個以上的goroutine中進(jìn)行通信,否則死鎖
代碼示例:
package main
import "fmt"
func main () {
ch := make(chan int)
ch <- 88
num :=<- ch
fmt.Println("讀到",num)
}
輸出結(jié)果:
fatal error: all goroutines are asleep - deadlock!
2竭望、goroutine之間channel訪問順序?qū)е滤梨i
使用channel一端讀(寫)挑辆,需要保證另一端寫(讀)
示例代碼:
package main
import "fmt"
func main () {
ch := make(chan int)
num :=<- ch
go func() {
ch <- 88
}()
fmt.Println("讀到",num)
}
輸出結(jié)果:
fatal error: all goroutines are asleep - deadlock!
正確的順序是:
package main
import "fmt"
func main () {
ch := make(chan int)
go func() {
ch <- 88
}()
num :=<- ch
fmt.Println("讀到",num)
}
結(jié)果:
讀到 88
3、多goroutine懦傍,多channel交叉死鎖。channel和mutex同時使用會產(chǎn)生交叉死鎖芦劣。
package main
func main () {
ch1 := make(chan int)
ch2 := make(chan int)
go func() {
for {
select {
case num1 := <- ch1:
ch2 <- num1
}
}
}()
for {
select {
case num2 := <- ch2:
ch1 <- num2
}
}
}
輸出結(jié)果:
fatal error: all goroutines are asleep - deadlock!
4粗俱、在go中,盡量不要將互斥鎖虚吟、讀寫鎖與channel混用 ------隱性死鎖 寸认。