Bradley Kirton's Blog

Published on July 10, 2023

Go home

Race Conditions

I recently completed the Programming with Google Go Specialisation on Coursera. I thought the course did a great job in defining a race condition.

A race condition is such that the desired outcome of a program depends on a specific ordering of task interleaving in a system in which task interleaving is non-deterministic.

Task interleaving refers to the switching and executing of instructions at a machine code level. To better illustrate this idea, suppose we have the following source code which defines a function which mutates some global state.

package main

import (
    "fmt"
    "sync"
)

var wg sync.WaitGroup
var i int

func inc() {
    i += 1
    wg.Done()
}

func main() {
    wg.Add(2)
    go inc()
    go inc()
    wg.Wait()
    fmt.Printf("The value of i is %d\n", i)
}

Let's assume inc function generates the following machine code instructions:

  1. read i
  2. inc
  3. write i

Given that we have no control over the scheduling of instruction execution, this in theory could result in the following interleaving:

Task 1Task 2Value of i
read i0
read i0
inc1
write i
inc1
write i