Select is switch/case for concurrency!

old-comics
concurrency
Published

November 20, 2023

Animals explain the select concurrency statement

An early try at programming-with-cartoons, in the spirit of _why’s Poignant Guide. Current work is at home.

read the transcript!

bubble 1: guy asks bird

What is select?

bubble 2: bird explains

It’s a control structure for concurrency. And Rob Pike, one of Golang’s developers, says it’s the reason channels and goroutines are built-in to the language.

bubble 3: guy asks “how does it work?”

Bird answers “It waits until 1 channel is ready. Kind of like case, and then runs the code in the corresponding branch.”

bubble 4: bird explains lines in Rob Pike’s example

{% highlight golang linenos %} select { case v1 := <-c1: fmt.Printf(“received %v from c1”, v1) case v2 := <-c2: // bird says here it is fanning in from c1 and c2 to stdout fmt.Printf(“received %v from c2”, v1) case c3 <- 23: fmt.Printf(“sent %v to c3”, 23) default: // giraffe says you can give a default if no channel is ready fmt.Printf(“no one was ready to communicate”) } {% endhighlight %}

Finally a cow explains if more than 1 channel is ready, then select picks on branch pseudorandomly.