Go: How Are Deadlocks Triggered?

Vincent
A Journey With Go
Published in
4 min readJul 11, 2020

--

Illustration created for “A Journey With Go”, made from the original Go Gopher, created by Renee French.

ℹ️ This article is based on Go 1.14.

A deadlock is a state that happens when a goroutine is blocked without any possibility to get unblocked. Go provides a deadlock detector that helps developers not get stuck in this kind of situation.

Detection

Let’s start with an example that creates this situation:

The main goroutine is blocked on the channel and waiting for another one to push data into the channel. However, no other goroutine is running, and it cannot be unblocked. This situation triggers the deadlock error:

The deadlock detector bases its analysis of the threads created by the application. There is a deadlock situation if the number of threads created and active is higher than the threads waiting for work.

The threads created to monitor the system are not included in this formula.

At the time the deadlock is detected, four threads are created:

  • One for the main goroutine, the one that starts the program.
  • One that monitors the system called sysmon.
  • One launched by the goroutines dedicated to the garbage collector.
  • One thread created when the main goroutine is blocked during the initialization. Since this goroutine is locked…

--

--