Fixing a Race Condition using a Mutex with Go (golang)

Post to Twitter

I was recently reading some articles on Go (golang) and it it got me to trying out a few techniques. New gophers may not know but Go allows you to compile your code to detect race conditions. Google has even implemented it into Go’s continuous build process where it will catch race conditions as they may get accidentally injected. Today I’ll show a simple example of how to check for race conditions in your Go code and along the way we will fix those race conditions using a Mutex.

Note: I’ll be using Go version 1.6.2 but prior versions from 1.1 onward should work. I’m also using Atom as my editor but you can of course use whatever you want.
Keep in mind these are meant to be simple/contrived examples to show off a race condition.

Let’s write some code that introduces a race condition.

Now run the code with the -race option:

$ go run -race main.go

Result:

In the Go routine reading to increment i
==================
WARNING: DATA RACE
Read by goroutine 6:
  main.main.func1()
      /Users/chadlung/GoProjects/src/github.com/chadlung/race-detection/main.go:17 +0x11d

Previous write by main goroutine:
  main.main()
      /Users/chadlung/GoProjects/src/github.com/chadlung/race-detection/main.go:22 +0xc5

Goroutine 6 (running) created at:
  main.main()
      /Users/chadlung/GoProjects/src/github.com/chadlung/race-detection/main.go:20 +0xa1
==================
New value of i: 2
Finished!
Found 1 data race(s)
exit status 66

You can see the race option quickly points out where our race condition happens as well as the fact we have a race condition. Let’s go ahead and fix this using a mutex.

$ go run -race main.go

Result:

In the Go routine reading to increment i
New value of i: 2
Finished!

According to the race tool the problem has now gone away.

Post to Twitter

This entry was posted in Go, Open Source. Bookmark the permalink.

3 Responses to Fixing a Race Condition using a Mutex with Go (golang)

  1. Gergely says:

    Hi.

    Your post has been referenced here, and there you can follow up on some comments people have wrote.

    https://www.reddit.com/r/golang/comments/4m2lcw/fixing_a_race_condition_using_a_mutex_with_go/

    Cheers.

  2. Chad Lung says:

    @Gergely,

    Thanks. I think people might be reading this beyond the simple/contrived example (now bolded in the article) it is to show a way to fix a particular problem using a mutex – not something else. The title of the article even states using a mutex.

    What also is interesting is the feedback here on Reddit:
    https://www.reddit.com/r/golang/comments/4jh7g9/handling_user_defined_signals_in_go
    – The race comments in particular there

    Chad

  3. Wuriyanto says:

    Hey Chad, thanks for your awesome works with GO,
    your Go articles help me a lot,
    i am new in GO and waiting for your new article about Go,,

Comments are closed.