For-Select blocks in Golang

Goroutines looping and checking status

Israel Josué Parra Rosales
2 min readAug 1, 2022

The for-select is used to coordinate channels and allow the communication each other. Help us to keep states between channels and goroutines and also could help us to handle with errors.

In adition we can say that select keyword is only used with channels. The select statement lets a goroutine wait on multiple communication operations. A select blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready.

in the select block we going to catch each one of the channels at time to be closed or if its value is set. In the following example we going to see an example about how the select block looks like.

This is not a functional example, is just to ilustrate how to implement it.

If we execute the following code we will get a deadlock error because all the goroutines are waiting because no one is setting or closing the channels.

But now if we close the channel 1 we going to do the thins defined on
select <-case1, example:

Output:
console output: from chan 1

If we need to wait by the two results is here when we implement a for loop and inside of it we define the select. in the following example we can see how we handle the two values, now we implements a quit channel that will help us to close the for-select loop.

This is not a applicable example is just to ilustrate how it works

Here the output will be the following:

from chan1
from chan2

Now we know the bases to usethe select and the for-select statements to handle with multiple channels.

Next Steps:
* Pipeline
* Thread Pool

This article is related to the Golang concurrency tutorial that you can find in the following link:

https://medium.com/@josueparra2892/concurrency-in-go-bf93e23bebd4

--

--

Israel Josué Parra Rosales

I'm a software developer with more than 11 years of experience. The last 9 years I have been working with Go. I love to learn and share my knowledge.