38

golang deadlock

 4 years ago
source link: https://www.tuicool.com/articles/jqYn22e
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

定义

deadlock:死锁,也称僵局,是指所有的gorountine都卡死(即无法继续执行下去)的一种异常状态。

发生deadlock时进程会直接退出,并抛出异常:

fatal error: all goroutines are asleep - deadlock!

一个最简单的例子

package main

func main() {
    ch := make(chan int)
    ch <- 1
}

由于该例子中的ch为无缓存通道,所以向ch写入会发生阻塞,导致卡死。执行该程序会报如下错误:

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan send]:
main.main()
        .../deadlock.go:5 +0x50
exit status 2

如果增加一个持续工作的协程,则不会发生deadlock。例如:

package main

import "fmt"

func main() {
    ch := make(chan int)

    go func(){
        for{
            fmt.Println("do sth.")
        }
    }()
    
    ch <- 1
}

如何避免

如何避免deadlock,则要从如何防止线程卡死方面入手,常见的线程卡死有以下两种情况

1. 锁操作的异常

比如lock一个永远无法unlock的锁。

2. channel的阻塞

比如上文中所举例子。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK