Sobes.tech
Junior — Middle

In what situations can deadlock of threads or processes occur?

sobes.tech AI

Answer from AI

A deadlock occurs when two or more threads or processes are waiting for resources held by each other, and none of them can proceed. The main situations leading to deadlock include:

  • Threads acquire multiple resources in different orders. For example, thread A has acquired resource 1 and is waiting for resource 2, while thread B has acquired resource 2 and is waiting for resource 1.
  • Use of locks (mutexes) without strict acquisition order.
  • Circular wait for resources.

In Go, this can happen due to improper use of mutexes, channels, or other synchronization primitives. For example, if two goroutines wait for each other through channels without timeouts or buffers.

To avoid deadlocks, you should:

  • Acquire resources in the same order.
  • Use timeouts or try-lock mechanisms that return errors.
  • Minimize the duration of lock holding.

An example of simple deadlock with mutexes in Go:

var mu1, mu2 sync.Mutex

func goroutine1() {
    mu1.Lock()
    defer mu1.Unlock()
    time.Sleep(time.Millisecond * 100)
    mu2.Lock()
    defer mu2.Unlock()
    // work
}

func goroutine2() {
    mu2.Lock()
    defer mu2.Unlock()
    time.Sleep(time.Millisecond * 100)
    mu1.Lock()
    defer mu1.Unlock()
    // work
}

Here, goroutine1 and goroutine2 can deadlock if the first has locked mu1 and the second mu2, and both are waiting for the other mutex to be released.

In what situations can deadlock of threads or… - sobes.tech