Switching between goroutines
This lesson explains how to transfer control between different goroutines via a channel.
We'll cover the following...
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