Select and Mutexes in Goroutines

Understand select statements and mutexes in the context of goroutines.

select statement

A select statement is similar to a switch statement but is geared toward listening to multiple channels. This allows us to receive and act on multiple inputs at the same time.

The following example will listen to several channels and execute a case statement whenever it receives a value on one of them. In the example cases, we spin off a goroutine to do something with the value so that we can continue the execution of our loop for the next value. If no value is present on the channel, this blocks until one is. If values are on more than one channel, select uses a pseudo-random method to select which case to execute:

Get hands-on with 1200+ tech skills courses.