Close this search box.

Golang: Go-routines and channels

Typically, if we ran a loop through a number of items, they happen serially (one after the other). But, something cool about Golang is the ability to run Go Routines.

We have the main routine by default and everything will sit within that routine. But, we can add concurrency to our scripts by spawning new go routines.

In the below, we spawn a new go routine for each run through of the checker function calls. We do that by simply adding ‘go’ infront of the call.

The problem with this is, once the main function has executed all of its code it kills the application, so we need to do something to keep the application alive until all of our go routines have completed. For this, we use channels.

Channels communicate between all the go routines and main routines so it knows when things have finished. In the below, we define our channel as channel := make(chan string) which defines a new channel, called channel. Inside the parenthesis we define that its a channel (chan) of type string. it’s important to note that channels are typed – a channel can only share information of that specific type.

Within the checker function, you see the notation channel <- link, this means we are sharing the value of the link variable with the channel.

Then, to keep the channel alive, we implement an infinite loop in the main function. Here, every time the checker function completes, it passes back the link back into the function. So, every time a website is checked a new job to check that website is immediately respawned.

The alternative to doing this (if you don’t want to perpetually run your job) is to implement the below, where the job listens for the response from the correct number of channels (i.e. if you are looping through a slice of 10 items, it waits until i increments to be 9 (which is 10 items from zero to nine).

Finally, this is an alternative method to define the infinite loop.

Share the Post:

Related Posts