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:
- Read the current value of
saldo. - Add one.
- Write the result back to
saldo.
Picture two coffee shop cashiers recording sales in the same ledger:
| Time | Cashier A | Cashier B | saldo |
|---|---|---|---|
| 1 | read 10 | 10 | |
| 2 | read 10 | 10 | |
| 3 | write 10 + 1 | 11 | |
| 4 | write 10 + 1 | 11 |
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, orLock(). That's why the result of the version without a mutex may be exactly the same on every Run here, and withoutruntime.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.