Sobes.tech
Middle

How to organize communication between goroutines and how to work with deadlocks?

sobes.tech AI

Answer from AI

The communication between goroutines in Go is usually organized through channels. Channels allow safe data transfer between goroutines and synchronization of their work.

Example of data transfer through a channel:

ch := make(chan int)
go func() {
    ch <- 42 // send value
}()
val := <-ch // receive value

To avoid deadlocks, you should:

  • Ensure that for each sender there is a receiver and vice versa.
  • Do not block a goroutine forever waiting for data that will never arrive.
  • Use buffered channels if you need to avoid blocking on send.
  • When using select, include default cases or timeouts.

A deadlock occurs when a goroutine is blocked forever waiting for an event that will not happen. The Go runtime detects deadlocks and panics.