Published on July 10, 2023
Go homeRace 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:
- read i
- inc
- write i
Given that we have no control over the scheduling of instruction execution, this in theory could result in the following interleaving:
Task 1 | Task 2 | Value of i |
---|---|---|
read i | 0 | |
read i | 0 | |
inc | 1 | |
write i | ||
inc | 1 | |
write i |