Tag Archives: pop quiz

Wednesday pop quiz: spot the race

The following program contains a data race

package main

import (

type RPC struct {
        result int
        done   chan struct{}

func (rpc *RPC) compute() {
        time.Sleep(time.Second) // strenuous computation intensifies
        rpc.result = 42

func (RPC) version() int {
        return 1 // never going to need to change this

func main() {
        rpc := &RPC{done: make(chan struct{})}

        go rpc.compute()         // kick off computation in the background
        version := rpc.version() // grab some other information while we're waiting
        <-rpc.done               // wait for computation to finish
        result := rpc.result

        fmt.Printf("RPC computation complete, result: %d, version: %d\n", result, version)

Where is the data race, and what is the smallest change that will fix it ?

Answer: the smallest change I know that will solve the race in this program is to change the receiver of the version method from RPC to *RPC.


The example above is derived from a larger, and more confusing example. You may be interested in the original race report.