Sobes.tech
Junior — Middle

In what cases does one goroutine stop executing and transfer control to another?

sobes.tech AI

Answer from AI

In Go, a goroutine stops executing and hands over control to another goroutine in the following cases:

  • When the goroutine explicitly calls a function that blocks it (for example, reading from a channel when the channel is empty).
  • When using the keyword runtime.Gosched(), which voluntarily yields the processor to other goroutines.
  • When the goroutine finishes its function (returns from the function), it stops executing.

The Go scheduler automatically switches execution between goroutines, ensuring concurrency. For example, when blocked on I/O operations or waiting for data from a channel, the current goroutine is suspended, and control is transferred to another.