Member-only story

Thread Safety in Golang

Pavle Djuric
5 min readJul 13, 2022

--

Goroutines are awesome. They are arguably the best solution for concurrency out there. However, your applications can get very unpredictable, and cause nasty bugs if you don’t use goroutines properly. One of the most important things to keep in mind is that if your goroutines are going to modify the state of any value stored in a memory address, you need to make them thread safe ( keep in mind that goroutines are actually just cheap threads) .

What exactly do I mean by this. Let me explain through an example:

Here is a very simple example. Say we have an application that is tracking the population of countries in real time. The population of a country is dynamic, babies get born all the time, and sadly some people pass away all the time.
The USA is a huge country, which consists of 50 states. So, for the sake of my example, this updatePopulation will simulate a single call to some Census Agency of every state. Since we're in a cheerful mood (and also because I need it to prove my point), we'll only register the newborns and not the departed.

--

--

Pavle Djuric
Pavle Djuric

Written by Pavle Djuric

Software developer. 3 x AWS certified. Writing mostly about Python, Golang, backend development and Cloud computing.

Responses (2)