Goroutines and Channels


In this article I will explain Goroutines and Channels using pizza in the examples because I love pizza and the metaphor of make and delivery pizza is a good way to exemplify concurrency tasks.


Lets start with a example that create pizzas without use the of goroutines:

The output of this program is:

Created Pizza 0
Created Pizza 1
Created Pizza 2
Build Pizzas took 3.006105234s


As we could see the function createPizza take 1 second to finish so to have 3 pizzas our program take 3 seconds to do it.

How could we improve our program in order to have the 3 pizzas in the same time that is created just 1 now?

The answer is creating pizzas at the same time. That is the kind of problem that goroutines was design to solve, below the goroutines definition:

A goroutine is a function that is capable of running concurrently with other functions. To create a goroutine we use the keyword go followed by a function invocation.

Knowing now the definition of goroutines, it is possible assume that we could use goroutines to prepare the pizzas at the same time as showed in the code below:

The output of this program is:

Created Pizza 0
Created Pizza 1
Created Pizza 2
Build Pizzas took 1.001509308s


As the output shows us, this new code using goroutines are able to create 3 pizzas in the same time, what increase the performance of our program a lot.

And as could be checked in the code just a few changes was added, what is amazing.

It was added in the code just the use of goroutines and sync.WaitGroup. The goroutines to execute the functions createPizza in parallel and the sync.WaitGroup to wait the goroutines return their results.


Other great tool that Golang provide us is the Channels, this data type enable us to pass data between goroutines easily.

As a way to exemplify the channels paradigm I have introduced in our program the idea of delivery pizzas putting pizzas in a channel that will synchronize the creation of the pizzas with the delivery service, as showed below.

The output of this program is:

Created Pizza 1
Motoboy 1 delivered pizza 1
Created Pizza 2
Motoboy 2 delivered pizza 2
Created Pizza 3
Motoboy 3 delivered pizza 3
Created Pizza 4
Motoboy 1 delivered pizza 4
Created Pizza 5
Motoboy 2 delivered pizza 5
Build Pizzas took 5.005705986s

Analyzing the output, it is possible realize that as a pizza is done it is delivered, this happens in the following way:

So the channel is the box where the createPizza goroutine put the pizza and the deliveryPizza get the pizza to delivery.


That is it folks, I hope my explanation about goroutines and channels help you to understand how and when use these 2 tools and I will be glad to hear from you comments and suggestions.

Like what you read? Give Geison a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.