doumao1519 2018-05-13 17:24
浏览 64
已采纳

Golang的“所有goroutine都睡着了-死锁!”错误背后的算法是什么?

Does the runtime keep a directed graph representing which goroutine waits for which somewhere? If so, could you point me to the relevant place in the source code?

I have not professionally coded in Go but noticed it has several nice features when I played with it.

  • 写回答

2条回答 默认 最新

  • dongyiba8082 2018-05-13 21:43
    关注

    You can check the Go source and easily find out: it happens in this function, which is called in various places where the program might enter a deadlock state.

    The relevant part is that the runtime gets the number of open OS threads, and checks how many of them are actually running code. There are a few more checks, but that's basically it. Whenever you run a blocking operation - such as as locking a mutex when it's already been locked elsewhere, or receiving from an empty channel - the scheduler will try to make the thread do the work of another goroutine. If none can be found, it enters an idle state.

    Basically, the scheduler always tries to find code that is waiting to be ran. If none can be found, then it's a deadlock situation.

    This of course excludes cases of, i.e., goroutines which are running time.Sleep, which although are "idling", there's a thread actively checking when they are ready to be run. In other words, they are not dependent on other parts of the program to start being "runnable" again (such as is the case for mutexes).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?