Non blocking code in Go (Part 1)

Mat Evans
HackerNoon.com
3 min readDec 7, 2016

--

Minimising Mutex’s.

This is mainly an exercise in examining ways in which you can write code in a non blocking style. The mutex available in the sync package is a perfectly acceptable way of protecting memory from bad things happening — un synced writers for example.

Also I should point out that “Share memory by communicating” very much still stands as a mantra you should keep in mind when writing Go.

There are a few examples of code that can block — either by using a mutex, or reading from a chan in a slow manner. Also there are certain data structure in Go that aren’t thread safe, for example maps, or bools.

Thread safe bool

In Go, the bool type isn’t inherently safe to use by multiple goroutines. We can protect it in a few ways.

This first bit of code shows how to use a simple mutex to lock a variable while it’s being updated.

Very simply, the mutex stops any other goroutine from updating the internal state of the SimpleBool struct when another goroutine has locked it.

Using Go’s built in benchmarking, it’s simple to see how this is performing.

--

--