Sobes.tech
Middle

Can Go detect deadlocks? How does the Go runtime detect deadlocks?

sobes.tech AI

Answer from AI

The Go runtime can detect deadlocks related to goroutines when all of them are blocked and there is no goroutine that can continue execution.

Detection occurs during goroutine scheduling: if the scheduler sees that all goroutines are in a waiting state (for example, on channels, mutexes, etc.) and none can be unblocked, the runtime panics with a deadlock message.

Example of a deadlock:

func main() {
    ch := make(chan int)
    ch <- 1 // blocks because there is no receiver
}

Here, the main goroutine is blocked on sending to a channel without a receiver, and the runtime will detect a deadlock.

Thus, the Go runtime automatically identifies situations where execution cannot continue due to mutual blocking of all goroutines.