Switching between goroutines

This lesson explains how to transfer control between different goroutines via a channel.

Waiting between a number of goroutines

Getting the values out of different, concurrently executing goroutines can be accomplished with the select keyword, which closely resembles the switch control statement, and is sometimes called the communications switch. It acts like an are you ready polling mechanism. The select listens for incoming data on channels, but there could also be cases where a value is not sent on a channel:

select {
  case u:= <- ch1:
    ...
  case v:= <- ch2:
    ...
    ...
  default: // no value ready to be received
    ...
}

The default clause is optional. The fall through behavior, like in the normal switch, is not permitted. A select is terminated when a break or return is executed in one of its cases. What select does is, it chooses which of the multiple communications listed by its cases can proceed.

  • If all are blocked, it waits until one can proceed.
  • When none of the channel operations can proceed, and the default clause is present, then this is executed because the default is always runnable, or ready to execute.
  • If multiple can proceed, it chooses one at random.

Using a send operation in a select statement with a default case guarantees that the send will be non-blocking! If there are no cases, the select blocks execution forever.

The select statement implements a kind of listener pattern, and it is mostly used within an (infinite) loop. When a certain condition is reached, the loop is exited via a break statement.

Look at the following program:

Get hands-on with 1200+ tech skills courses.