Go course

MutexesRace Conditions

Go

Display

Theme

Mutexes · Code example

Race Conditions

In the previous chapter we ran lots of goroutines at once. Trouble starts when several goroutines read and write the same variable at the same time. This is called a race condition: the program's final result depends on an execution order you can't control.

Why isn't x++ safe?

An operation as simple as saldo++ is really three steps:

  1. Read the current value of saldo.
  2. Add one.
  3. Write the result back to saldo.

Picture two coffee shop cashiers recording sales in the same ledger:

TimeCashier ACashier Bsaldo
1read 1010
2read 1010
3write 10 + 111
4write 10 + 111

Two sales happened, but saldo only went up by one. One of the updates got lost (a lost update).

Waiting for goroutines with sync.WaitGroup

For the examples in this chapter we use sync.WaitGroup so main waits for every goroutine to finish:

var wg sync.WaitGroup
for i := 0; i < 3; i++ {
	wg.Add(1)        // satu goroutine lagi yang harus ditunggu
	go func() {
		defer wg.Done() // tandai selesai
		// ... kerjakan sesuatu
	}()
}
wg.Wait() // blok sampai semua memanggil Done

Making the race more likely

In small programs, races can be hard to spot. The example in the editor slips a runtime.Gosched() between the read and write steps. That function asks the Go scheduler to run other goroutines first, just like a cashier getting "distracted" halfway through recording a sale. As a result, lost updates are almost guaranteed.

The fix: a mutex

A mutex (mutual exclusion) is a lock that makes sure only one goroutine can run a particular piece of code (called the critical section) at a time:

var mu sync.Mutex

mu.Lock()   // goroutine lain yang memanggil Lock akan menunggu di sini
saldo++
mu.Unlock() // buka kunci, giliran goroutine berikutnya

Go comes with a race detector (go test -race / go run -race) that can find races automatically. It isn't available on this platform, so we rely on checking the final result instead.

Try it yourself

Run the example in the editor with Run. The version without a mutex comes out below 1000, while the version with a mutex is always exactly 1000. Also try deleting the runtime.Gosched() line and compare the results.

A note on the Go runtime in Nibble: the Go runtime in your browser runs every goroutine on a single thread. Goroutines only take turns at certain points, such as runtime.Gosched(), channel operations, or Lock(). That's why the result of the version without a mutex may be exactly the same on every Run here, and without runtime.Gosched() you might not see the race at all. With Go installed on your own computer, goroutines run in parallel across many cores, so the result changes from one run to the next. The tests in this chapter don't rely on races: they check directly that your methods wait for the mutex lock.

main.go
package main

import (
	"fmt"
	"runtime"
	"sync"
)

// tanpaMutex menambah penjualan dari banyak goroutine TANPA pengaman.
func tanpaMutex(jumlahKasir int) int {
	penjualan := 0
	var wg sync.WaitGroup
	for i := 0; i < jumlahKasir; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			sementara := penjualan    // 1. baca
			runtime.Gosched()         // kasir "terdistraksi"
			penjualan = sementara + 1 // 2-3. tambah lalu tulis
		}()
	}
	wg.Wait()
	return penjualan
}

// denganMutex melakukan hal yang sama, tetapi dijaga oleh sync.Mutex.
func denganMutex(jumlahKasir int) int {
	penjualan := 0
	var mu sync.Mutex
	var wg sync.WaitGroup
	for i := 0; i < jumlahKasir; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			mu.Lock()
			sementara := penjualan
			runtime.Gosched()
			penjualan = sementara + 1
			mu.Unlock()
		}()
	}
	wg.Wait()
	return penjualan
}

func main() {
	fmt.Println("Tanpa mutex :", tanpaMutex(1000))
	fmt.Println("Dengan mutex:", denganMutex(1000))
}

Output

Go runtime not loaded yet

Press Run to see what the program prints.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + S: tidy the code (gofmt)