HN 日本語サマリー

← 一覧へ戻る
プログラミング

Goの並行処理を凝縮

Go Concurrency Distilled (antonz.org)

401 pointsby chmaynard187 コメント

要約

このミニブックは、Goにおける多くの並行処理トピックの概要を簡潔に提供します。各トピックにはインタラクティブな例が含まれており、コードを変更して実行することで自由に試すことができます。PDF版も用意されています。これはGoの並行処理のクイックリフレッシャーであり、初心者向けガイドではありません。実践的な演習で並行処理をゼロから学びたい場合は、別の書籍「Gist of Go: Concurrency」を参照してください。

全文翻訳

Goの並行処理を凝縮

このミニブックは、Goにおける並行処理の多くのトピックを簡潔に概観します。各トピックにはインタラクティブなサンプルが付属しています — コードを変更して実行をクリックすることで、自由に試してみてください。静的なサンプルを含むPDF版もあります。

これはGoの並行処理のクイックリフレッシャーであり、初心者向けのガイドではありません。実践的な演習を通して並行処理を一から学びたい場合は、私の別の本 — Gist of Go: Concurrencyをご覧ください。

この本はAIフリーです。

Goroutines • Channels • Select • Pipelines • Time • Context • Wait groups • Data races • Race conditions • Mutexes • Semaphores • Signaling • Run once • Object pool • Atomics • Testing • Scheduling • Diagnostics • Final thoughts

# Goroutines

Goにおける並行処理の基盤はgoroutinesです — goキーワードで開始される関数です。

func main() {
    var wg sync.WaitGroup
    wg.Add(2)
    go func() {
        defer wg.Done()
        fmt.Println("worker 1")
    }()
    go func() {
        defer wg.Done()
        fmt.Println("worker 2")
    }()
    wg.Wait()
}
worker 2
worker 1

Goランタイムはこれらのgoroutineを管理し、CPUコアで実行されているオペレーティングシステムのスレッドに分散させます。OSスレッドと比較して、goroutineは軽量であるため、数百または数千ものgoroutineを作成できます。

Goroutineは完全に独立しています。main関数もgoroutineですが、プログラム開始時に暗黙的に開始されます。mainが終了すると、他のgoroutineもシャットダウンします。

上記の例では、goroutineの完了を待つためにwait group (sync.WaitGroup)を使用します。Wait groupは内部にカウンタを持っています。Add(n)を呼び出すとカウンタがnだけ増加し、Done()は1つずつデクリメントします。Wait()は、カウンタがゼロになるまで呼び出し元のgoroutine(この場合はmain)をブロックします。これにより、mainは両方のワーカーが終了するのを待ってから終了します。

WaitGroup.Goは、Wait groupカウンタを自動的にインクリメントし、goroutineで関数を実行し、完了時にカウンタをデクリメントします。

func main() {
    var wg sync.WaitGroup
    wg.Go(func() {
        fmt.Println("worker 1")
    })
    wg.Go(func() {
        fmt.Println("worker 2")
    })
    wg.Wait()
}
worker 2
worker 1

# Channels

Goroutineはchannelsを通じて互いに値を渡すことができます。Channelは、一方のgoroutineが何かを投げ込み、もう一方がそれをキャッチできるウィンドウのようなものです。

func main() {
    messages := make(chan string)

    go func() {
        messages <- "ping"
    }()

    msg := <-messages
    fmt.Println(msg)
}
ping

Channelへの値の送信は同期的な操作です。送信元のgoroutineがChannelに値(ch <- val)を書き込むと、ブロックして誰かがその値を受け取る(<-ch)のを待ちます。その後、処理を続行します。

Output channel

関数から出力Channelを返し、内部のgoroutineでそれを埋めるのは、Goで一般的なパターンです。これにより、呼び出し元はChannelを通じて値を受け取ることができ、所有する関数はそれを制御下に置くことができます。

func generate(start, stop int) chan int {
    out := make(chan int)
    go func() {
        for i := start; i < stop; i++ {
            out <- i
        }
    }()
    return out
}
Closing a channel

すべてのデータが送信されたことをリーダーに通知するために、ライターgoroutineはclose()でChannelをクローズします。

func generate(start, stop int) chan int {
    out := make(chan int)
    go func() {
        defer close(out)
        for i := start; i < stop; i++ {
            out <- i
        }
    }()
    return out
}

リーダーは、読み取る際に2番目の値("comma OK")でChannelの状態を確認します。

func main() {
    in := generate(5, 10)
    for {
        num, ok := <-in
        if !ok {
            break
        }
        fmt.Print(num, " ")
    }
}
5 6 7 8 9 

Channelが開いている間、リーダーは次の値とtrueの状態を受け取ります。Channelが閉じられると、リーダーはゼロ値とfalseの状態を受け取ります。

Channelは一度しかクローズできません。再度クローズしたり、クローズされたChannelに書き込んだりするとパニックが発生します。

Channelをクローズする唯一の理由は、すべてのデータが送信されたことをリーダーに通知することです。これがリーダーにとって重要でない場合、クローズする必要はありません。Channelが使用されなくなると、Goのガベージコレクタは、クローズされているかどうかにかかわらず、そのリソースを解放します。

Channel iteration

rangeは自動的にChannelから次の値を取得し、それがクローズされているかを確認します。Channelがクローズされている場合、ループを終了します。

func main() {
    nums := generate(5, 10)
    for n := range nums {
        fmt.Print(n, " ")
    }
}
5 6 7 8 9 

Channelに対するRangeは、スライスに対するRangeとは異なり、単一の値(ペアではない)を返します。

Directional channels

Channelの方向を設定することで、誤った書き込み/クローズエラーから自身を保護できます。Channelは次のようになります。

  • chan (双方向): 読み書き用(デフォルト)
  • chan<- (送信専用): 書き込み専用
  • <-chan (受信専用): 読み取り専用

送信専用Channelから読み取ったり、受信専用Channelに書き込んだりすることはできません(クローズすることもできません)。

Channelは通常、読み書き両方で初期化され、関数パラメータで方向が指定されます。Goは通常のChannelを自動的に方向付きのChannelに変換します。

stream := make(chan int)

go func(in chan<- int) {
    in <- 42
}(stream)

func(out <-chan int) {
    fmt.Println(<-out)
}(stream)
42
Buffered channels

Buffered channelsは、固定サイズのバッファを持つFIFOキューのように機能し、値を格納します。

バッファに空きがある限り、Channelへの書き込みはgoroutineをブロックしません。同様に、バッファに値が含まれている限り、Channelからの読み取りはgoroutineをブロックしません。

stream := make(chan int, 3)
stream <- 11
stream <- 12
stream <- 13

fmt.Println(<-stream)
fmt.Println(<-stream)
11
13

デフォルトでは、バッファサイズを指定しない場合、Channelはunbuffered(バッファサイズゼロ)になります。

Buffered channelsは、組み込みのlen()およびcap()関数で機能します。

stream := make(chan int, 3)
stream <- 11
fmt.Println(cap(stream), len(stream))
3 1

クローズされたBuffered channelからの読み取りは、バッファ内の値を返し、trueの状態を返します。すべての値が取得されると、通常のChannelと同様にゼロ値とfalseの状態を返します。

stream := make(chan int, 1)
stream <- 11
close(stream)

val, ok := <-stream
fmt.Println(val, ok)
// 11 true

val, ok = <-stream
fmt.Println(val, ok)
// 0 false
11 true
0 false
nil channel

Goの他の型と同様に、Channelにはゼロ値があり、それはnilです。

nil Channelへの書き込みまたはnil Channelからの読み取りは、goroutineを無期限にブロックします。

var stream chan int

go func() {
    // blocks forever
    stream <- 1
}()

// blocks forever
<-stream

nil Channelのクローズはパニックを引き起こします。

var stream chan int
close(stream)
// panic: close of nil channel

# Select

selectステートメントはswitchに似ていますが、Channel専用に設計されています。その機能は以下の通りです。

  • ブロックされていないケースをチェックします。
  • 複数のケースが準備できている場合、ランダムに1つを選択して実行します。
  • すべてのケースがブロックされており、defaultケースがある場合、それを実行します。
  • すべてのケースがブロックされており、defaultケースがない場合、1つが準備できるまで待機します。

Selectはパイプラインでのデータフローを管理するために使用されます。

// mergeはin1とin2からの値を出力Channelに送信します。
func merge(in1, in2 <-chan int) <-chan int {
    out := make(chan int)
    go func() {
        defer close(out)
        for in1 != nil || in2 != nil {
            select {
            case val1, ok := <-in1:
                if ok { out <- val1 } else { in1 = nil }
            case val2, ok := <-in2:
                if ok { out <- val2 } else { in2 = nil }
            }
        }
    }()
    return out
}

// in1に10..12、in2に20..22を送信し、
// merge(in1, in2)を呼び出すと仮定します。
10 11 20 12 21 22

Goroutineをキャンセルするには:

// processはinからの値を変更し、outに送信します。
// inが枯渇するか、cancelがクローズされるまで。
func process(cancel chan struct{}, in <-chan int) <-chan int {
    out := make(chan int)
    go func() {
        for val := range in {
            select {
            case out <- val*10:
            case <-cancel:
                fmt.Println("canceled")
                return
            }
        }
    }()
    return out
}

// inに値11と12を送信し、
// その後close(cancel)を呼び出すと仮定します。
110
120
canceled

非ブロッキング操作のために:

// multiplierは、入力を10倍してChannelに送信するか、
// Channelがビジーの場合はエラーを返す関数を返します。
func multiplier(ch chan<- int) func(n int) error {
    return func(n int) error {
        select {
        case ch <- n*10:
            return nil
        default:
            return errors.New("busy")
        }
    }
}

func main() {
    nums := make(chan int, 1)
    multiply := multiplier(nums)

    err := multiply(11)
    fmt.Println(<-nums, err)
    // 110 <nil>

    err = multiply(12)
    fmt.Println(<-nums, err)
    // 120 <nil>

    err = multiply(13)
    err = multiply(14)
    fmt.Println(err)
    // busy
}
110 <nil>
120 <nil>
busy

そして、さらに多くの用途があります。

# Pipelines

A pipelineは、各ステップが入力データを取得し、特定の方式で処理し、出力する一連の操作です。各操作の入力と出力はChannelです。

典型的なパイプラインは次のようになります。

  • Reader: ファイル、データベース、またはネットワークから入力データを読み取ります。
  • N processors: 外部ソースを使用してデータを変換、フィルタリング、集計、またはエンリッチします。
  • Writer: 処理されたデータをファイル、データベース、またはネットワークに書き込みます。
func read[T any]() <-chan T {
    out := make(chan T)
    go func() {
        defer close(out)
        for {
            // read data from somewere
            data := // ...
            out <- data
        }
    }()
    return out
}

func process[T any](in <-chan T) <-chan T {
    out := make(chan T)
    go func() {
        defer close(out)
        for inData := range in {
            // process the data
            outData = // ...
            out <- outData
        }
    }()
    return out
}

func write[T any](in <-chan T) <-chan struct{} {
    done := make(chan struct{})
    go func() {
        defer close(done)
        for data := range in {
            // write the data
        }
    }()
    return done
}
Output channel

Goroutineは、output channelを使用して、作業が完了したことを他のgoroutineに通知できます。

func generate(start, stop int) <-chan int {
    out := make(chan int)
    go func() {
        defer close(out)
        for i := start; i < stop; i++ {
            out <- i
        }
    }()
    return out
}

func main() {
    nums := generate(5, 10)
    for n := range nums {
        fmt.Print(n, " ")
    }
}
5 6 7 8 9 
Done channel

Goroutineが結果を返す必要がない場合、done channelを使用して完了を通知できます。

func work() <-chan struct{} {
    done := make(chan struct{})
    go func() {
        defer close(done)
        fmt.Println("work done")
    }()
    return done
}

func main() {
    done := work()
    <-done
}
work done
Cancel channel

Goroutineを早期に終了させるために、呼び出し元のgoroutineはcancel channelを使用できます。

func generate(cancel chan struct{}, n int) <-chan int {
    out := make(chan int)
    go func() {
        defer close(out)
        for i := 1; i <= n; i++ {
            select {
            case out <- i:
            case <-cancel:
                return
            }
        }
    }()
    return out
}

func main() {
    cancel := make(chan struct{})
    defer close(cancel)

    nums := generate(cancel, 10)
    fmt.Println(<-nums)
    fmt.Println(<-nums)
    fmt.Println(<-nums)
}
1
2
3
Error handling

並行パイプラインでのエラー処理には3つのアプローチがあります。

➊ エラー発生時に終了:

// calculateは与えられた数値に対する回答を生成します。
func process(in <-chan int) (<-chan int, <-chan error) {
	out := make(chan Answer)
	errc := make(chan error, 1)
	go func() {
		defer close(out)
		for n := range in {
			ans, err := fetchAnswer(n)
			if err != nil {
				errc <- err  // エラーで終了
				return
			}
			out <- ans
		}
		errc <- nil          // nilで終了
	}()
	return out, errc
}

➋ 結果型を使用:

// Resultは回答またはエラーを含みます。
type Result struct {
	answer int
	err    error
}

// calculateは与えられた数値に対する回答を生成します。
func calculate(in <-chan int) <-chan Result {
	out := make(chan Result)
	go func() {
		defer close(out)
		for n := range in {
			ans, err := fetchAnswer(n)
			out <- Result{ans, err}  // 回答+エラーを返す
		}
	}()
	return out
}

➌ エラーを個別に収集:

// calculateは与えられた数値に対する回答を生成します。
func calculate(in <-chan int, errc chan<- error) <-chan int {
	out := make(chan Answer)
	go func() {
		defer close(out)
		for n := range in {
			ans, err := fetchAnswer(n)
			if err == nil {
				out <- ans   // 回答を送信
			} else {
				errc <- err  // またはエラー
			}
		}
	}()
	return out
}

# Time

日付と時刻の処理に加えて、timeパッケージは並行プログラムでの時間制約のある操作を管理するためのツールを提供します。

After

time.After()は、最初は空ですが、タイムアウト期間後に値を受け取るChannelを返します。これは、操作のタイムアウトに役立ちます。

// withTimeoutは指定されたタイムアウトで関数を実行します。
func withTimeout(timeout time.Duration, fn func()) error {
    done := make(chan struct{})
    go func() {
        defer close(done)
        fn()
    }()

    // fnが完了するか、タイマーが期限切れになるまでブロックします。
    // 先に発生した方が優先されます。
    select {
    case <-done:
        return nil
    case <-time.After(timeout):
        return errors.New("timeout")
    }
}

withTimeout()はfn()の完了を待ちますが、time.After()のおかげで、timeout期間以上待つことはありません。

func main() {
    var err error

    // 時間内に完了
    err = withTimeout(
        50*time.Millisecond,
        func() { fmt.Println("work done") },
    )
    fmt.Println("err =", err)

    // タイムアウトでキャンセル
    err = withTimeout(
        50*time.Millisecond,
        func() {
            time.Sleep(100 * time.Millisecond)
            fmt.Println("work done")
        },
    )
    fmt.Println("err =", err)
}
work done
err = <nil>
err = timeout
Timer

timer (time.Timer)は、トリガー(期限切れ)時に現在の時間を送信するC Channelを持つ構造体です。タイマーは将来の実行を計画するのに役立ちます。

done := make(chan struct{})

timer := time.NewTimer(50 * time.Millisecond)
go func() {
    eventTime := <-timer.C  // 50ms待機
    fmt.Println("work done at", eventTime)
    close(done)
}()

<-done
work done at 2009-11-10 23:00:00.05

Stop()はタイマーを停止し、まだ期限切れでない場合はtrueを、そうでない場合はfalseを返します。

// timerは50ms後に期限切れになります
timer := time.NewTimer(50 * time.Millisecond)
go func() {
    eventTime := <-timer.C
    fmt.Println("work done at", eventTime)
}()

// 10ms後、タイマーはまだ期限切れではありません
time.Sleep(10 * time.Millisecond)

if timer.Stop() {
    fmt.Println("execution canceled")
} else {
    fmt.Println("too late to cancel")
}
execution canceled

time.AfterFunc()ラッパー関数を使用すると、より便利です。これは期間d待機してから関数fを実行します。

done := make(chan struct{})
work := func() {
    fmt.Println("work done")
    close(done)
}

// 50ms後にworkを実行
time.AfterFunc(50*time.Millisecond, work)
<-done
work done

time.AfterFunc()は、実行前にキャンセルできるタイマーを返します。

// 50ms後に関数を実行
timer := time.AfterFunc(50*time.Millisecond, func() {}) 

// 10ms後、タイマーはまだ期限切れではありません
time.Sleep(10 * time.Millisecond)

if timer.Stop() {
    fmt.Println("execution canceled")
}
execution canceled

ループ内でタイマーを使用する場合、新しいインスタンスを各イテレーションで作成するのではなく、単一のタイマーを作成してリセットする方が良いです。

// consumerは入力Channelからトークンを読み取り、
// 1時間経過しても値が表示されない場合は警告を発します。
func consumer(in <-chan token) {
    const timeout = time.Hour
    timer := time.NewTimer(timeout)
    for {
        timer.Reset(timeout)
        select {
        case <-in:
            // do stuff
        case <-timer.C:
            // log warning
        }
    }
}

// in Channelに10,000個の値を送信し、
// メモリ使用量を測定すると仮定します。
Memory used: 4 KB, # allocations: 6
Ticker

tickerはタイマーに似ていますが、停止されるまで継続的に発火します。Tickerは定期的なタスクを実行するのに役立ちます。

// 50msごとに発火
ticker := time.NewTicker(50 * time.Millisecond)
defer ticker.Stop()

go func() {
    for {
        // 各イテレーションでtickerが発火するのを待ちます
        at := <-ticker.C
        fmt.Println("work done at", at)
    }
}()

// tickerが3回発火するのに十分な時間
time.Sleep(160*time.Millisecond)
ticker.Stop()
work done at 2009-11-10 23:00:00.05
work done at 2009-11-10 23:00:00.10
work done at 2009-11-10 23:00:00.15

NewTicker(d)は、間隔dでChannel Cに現在の時間を送信するtickerを作成します。リソースを解放するために、最終的にはStop()でtickerを停止する必要があります。

Channelリーダーがtickerに追いつけない場合、tickerはティックをスキップします。

# Context

contextの主な目的は、手動またはタイムアウト/デッドラインによって操作をキャンセルすることです。

関数はcontextを受け入れ、そのDone() Channelを使用してキャンセレーションをリッスンします。

// workはキャンセルされない限り50msの間タスクを実行します。
// キャンセルされた場合にエラーを返します。
func work(ctx context.Context) error {
    done := make(chan struct{})

    go func() {
        time.Sleep(50 * time.Millisecond)
        fmt.Println("work done")
        close(done)
    }()

    select {
    case <-done:
        return nil
    case <-ctx.Done():
        return ctx.Err()
    }
}

手動でキャンセル(context.Canceledエラー):

func main() {
    // 空のcontext
    ctx := context.Background()
    // 手動キャンセルcontext
    ctx, cancel := context.WithCancel(ctx)
    defer cancel()

    done := make(chan struct{})
    go func() {
        // 10msでキャンセルされない限り50msかかります
        err := work(ctx)
        fmt.Println("err =", err)
        close(done)
    }()

    // 10ms後にキャンセル
    time.Sleep(10 * time.Millisecond)
    cancel()
    <-done
}
err = context canceled

タイムアウトによるキャンセル(context.DeadlineExceededエラー):

func main() {
    ctx := context.Background()
    // 10ms後にキャンセル
    ctx, cancel := context.WithTimeout(ctx, 10*time.Millisecond)
    defer cancel()

    done := make(chan struct{})
    go func() {
        // 50msかかりますが、キャンセルされるまで
        err := work(ctx)
        fmt.Println("err =", err)
        close(done)
    }()

    <-done
}
err = context deadline exceeded

デッドラインによるキャンセル(context.DeadlineExceededエラー):

func main() {
    ctx := context.Background()
    // 現在時刻+10msにキャンセル
    deadline := time.Now().Add(10 * time.Millisecond)
    ctx, cancel := context.WithDeadline(ctx, deadline)
    defer cancel()

    done := make(chan struct{})
    go func() {
        // 50msかかりますが、キャンセルされるまで
        err := work(ctx)
        fmt.Println("err =", err)
        close(done)
    }()

    <-done
}
err = context deadline exceeded

Contextは階層化されています。Contextオブジェクトは不変です。Contextに新しいプロパティを追加するには、古い(親)Contextに基づいて新しい(子)Contextが作成されます。親と子のContextの間の短い方のタイムアウトが常に優先されます。子Contextは親のタイムアウトを短縮することはできますが、延長することはできません。

func main() {
    // 100msのタイムアウトを持つ親Context
    const dur100ms = 100 * time.Millisecond
    parentCtx, cancel := context.WithTimeout(context.Background(), dur100ms)
    defer cancel()

    // 10msのタイムアウトを持つ子Context
    const dur10ms = 10 * time.Millisecond
    childCtx, cancel := context.WithTimeout(parentCtx, dur10ms)
    defer cancel()

    // now the work gets canceled
    err := work(childCtx)
    fmt.Println("err =", err)
}
err = context deadline exceeded

複数のキャンセルは安全です。Contextに対してcancel()を何度でも呼び出すことができます。最初のキャンセルは機能し、残りは無視されます。

You can specify a custom cancellation cause using context.WithCancelCause(), context.WithTimeoutCause() and context.WithDeadlineCause(). This cause is accessible through context.Cause():

ctx, cancel := context.WithCancelCause(context.Background())
cancel(errors.New("the night is dark"))
fmt.Println(context.Cause(ctx))
the night is dark

Contextがキャンセルされたときに実行される関数をcontext.AfterFunc()で登録できます。

ctx, cancel := context.WithCancel(context.Background())
cleanup := func() { fmt.Println("cleanup") }
context.AfterFunc(ctx, cleanup)
cancel()
time.Sleep(10 * time.Millisecond)
cleanup

Contextはcontext.WithValue()を使用して追加情報を呼び出し元に渡すことができます。これは特定のキーに対する値を持つContextを作成します。しかし、一般的にはContextで値を渡すことは避けるべきです。明示的なパラメータやカスタム構造体を使用する方が良いでしょう。

# Wait groups

sync.WaitGroup型を使用すると、1つ以上のgoroutineの完了を待つことができます。

const n = 10
var wg sync.WaitGroup
wg.Add(n)
for range n {
    go func() {
        defer wg.Done()
        fmt.Print(".")
    }()
}
wg.Wait()
..........

WaitGroupは、それが管理するgoroutineについては何も知りません。内部カウンタで動作します。wg.Add(1)を呼び出すとカウンタが1つ増加し、wg.Done()はそれをデクリメントします。wg.Wait()は、グループのカウンタがゼロになるまで呼び出し元のgoroutineをブロックします。

GoメソッドはAdd、goroutineの開始、およびDoneを組み合わせます。

var wg sync.WaitGroup
for range 10 {
    wg.Go(func() {
        fmt.Print(".")
    })
}
wg.Wait()
..........

すべてのメソッドは複数のgoroutineから安全に使用できます。

通常、すべてのAdd呼び出しはWaitの前に行われます。しかし、技術的には、Waitの前に一部のAdd呼び出しを行い、後で(別のgoroutineから)行うことを妨げるものはありません。

複数のgoroutineからWaitを呼び出すことができます。それらはすべて、グループのカウンタがゼロに達するまでブロックされます。

# Data races

データレースは、複数のgoroutineが共有データにアクセスし、そのうち少なくとも1つがそれを変更する場合に発生します。この種の同時アクセスからデータを保護する必要があります。

A data race doesn't always cause a runtime panic. That's why Go provides a special tool called the race detector. You can turn it on with the race flag, which works with the test, run, build, and install commands.

var total int

// There's a data race on total.
var wg sync.WaitGroup
wg.Go(func() { total++ })
wg.Go(func() { total++ })
wg.Wait()

fmt.Println("total:", total)
total: 2
go run -race main.go
==================
WARNING: DATA RACE
...
2
Found 1 data race(s)

Channelは同時読み書きに安全であり、データレースを引き起こしません。

データレースを防ぐ方法:

  • 同時データ変更を避ける(通常はChannelを使用)。
  • ミューテックスでアクセスを同期する。
  • アトミック操作のみを使用する。

Race conditions

A race condition happens when an unpredictable order of operations from multiple goroutines leads to an incorrect system state:

// There's a race condition when working with balance.
withdraw := func(amount int) {
    if getBalance() < amount {
        return
    }
    time.Sleep(time.Millisecond)
    setBalance(getBalance() - amount)
}

setBalance(50)

var wg sync.WaitGroup
wg.Go(func() { withdraw(40) })
wg.Go(func() { withdraw(40) })
wg.Wait()

fmt.Println("balance:", getBalance())
balance: -30

個々の操作が同時実行安全であっても、Goのレース検出器は問題を見つけません。このため、レースコンディションを検出できません。

go run -race main.go
balance: -30

同時実行環境における不確実性を完全に排除することはできません。イベントは予測不可能な順序で発生します — それが同時実行の仕組みです。しかし、レースコンディションを防ぐことはできます — 多くの場合、複合操作をミューテックスで保護することによって行います。

var mu sync.Mutex
withdraw := func(amount int) {
    mu.Lock()
    defer mu.Unlock()

    if getBalance() < amount {
        return
    }
    time.Sleep(time.Millisecond)
    setBalance(getBalance() - amount)
}

setBalance(50)

var wg sync.WaitGroup
wg.Go(func() { withdraw(40) })
wg.Go(func() { withdraw(40) })
wg.Wait()

fmt.Println("balance:", getBalance())
balance: 10
Compare-and-set

ミューテックスを使用せずにレースコンディションを防ぐことができる場合があります。アトミックな比較・交換(compare-and-set)操作またはそのバリエーションを適用することによって行います。

// CompareAndSetは、現在の値がoldと等しい場合に値をnewに変更します。
// 値が変更された場合はtrueを返します。
CompareAndSet(old, new any) bool

// CompareAndSwapは、現在の値がoldと等しい場合に値をnewに変更します。
// old値を返します。
CompareAndSwap(old, new any) any

// CompareAndDeleteは、現在の値がoldと等しい場合に値を削除します。
// 値が削除された場合はtrueを返します。
CompareAndDelete(old any) bool

// etc

アイデアは常に同じです。

  • 想定される(古い)状態が現実と一致するかどうかを確認します。
  • 一致する場合、状態を新しいものに変更します。
  • 一致しない場合、何も行いません。

# Mutexes

sync.Mutex型は、共有データとコードの一部を同時アクセスから保護します。

var total int
var mu sync.Mutex

var wg sync.WaitGroup
for range 100 {
    wg.Go(func() {
        mu.Lock()
        time.Sleep(time.Millisecond)
        total++
        mu.Unlock()
    })
}
wg.Wait()
total: 100

ミューテックスは、Lock()とUnlock()の間にあるコードを一度に1つのgoroutineしか実行できないことを保証します。

ミューテックスは次のような状況で使用されます。

  • 複数のgoroutineが同じデータを変更している場合。
  • 1つのgoroutineがデータを変更し、他のgoroutineがそれを読み取っている場合。

すべてのgoroutineがデータを読み取っているだけの場合、ミューテックスは必要ありません。

TryLock

TryLockメソッドは、通常のLockと同様にミューテックスをロックしようとします。しかし、ロックできない場合は、ブロックせずにすぐにfalseを返します。

var total int
var mu sync.Mutex

var wg sync.WaitGroup
for range 100 {
    wg.Go(func() {
        if !mu.TryLock() {
            return
        }
        defer mu.Unlock()
        time.Sleep(time.Millisecond)
        total++
    })
}
wg.Wait()
total: 1
RWMutex

sync.RWMutex型は、リーダーとライターを区別します。2つのメソッドセットを提供します。

  • Lock / Unlockは、読み取りと書き込みの両方に対してミューテックスをロックおよびアンロックします。
  • RLock / RUnlockは、読み取り専用でミューテックスをロックおよびアンロックします。
var total int
var mu sync.RWMutex
var wg sync.WaitGroup

// 10人のライター。
for range 10 {
    wg.Go(func() {
        mu.Lock()
        defer mu.Unlock()
        time.Sleep(time.Millisecond)
        total++
    })
}

// 10人のリーダー。
for range 10 {
    wg.Go(func() {
        // RLock/RUnlockからLock/Unlockに切り替えてみて、
        // 経過時間にどのように影響するか確認してください。
        mu.RLock()
        defer mu.RUnlock()
        time.Sleep(time.Millisecond)
        _ = total
    })
}

wg.Wait()
elapsed: 10ms

仕組みは次のとおりです。

  • あるgoroutineがLock()でミューテックスをロックした場合、他のgoroutineがLock()またはRLock()を使用しようとするとブロックされます。
  • あるgoroutineがRLock()でミューテックスをロックした場合、他のgoroutineもブロックされずにRLock()でロックできます。
  • 少なくとも1つのgoroutineがRLock()でミューテックスをロックしている場合、他のgoroutineはLock()を使用しようとするとブロックされます。

これにより、「単一ライター、複数リーダー」のセットアップが作成されます。

Locker

sync.Mutexとsync.RWMutexの両方が同じsync.Lockerインターフェースを実装しています。

type Locker interface {
    Lock()
    Unlock()
}

特定のミューテックス型ではなくLockerを使用することで、特定のロック実装に依存しないコンポーネントを構築できます。これにより、クライアントがどのロックを使用するかを決定できます。

Channel as mutex

ミューテックスの代わりにChannelを使用して共有データを保護できます。

var total int
lock := make(chan struct{}, 1)

var wg sync.WaitGroup
wg.Go(func() {
    lock <- struct{}{}
    defer func() { <-lock }()
    total++
})
wg.Go(func() {
    lock <- struct{}{}
    defer func() { <-lock }()
    total++
})
wg.Wait()
total: 2

# Semaphores

A semaphore is like a container with N available slots and two operations: acquire to take a slot and release to free a slot. Here are the semaphore rules:

  • Calling acquire takes a free slot.
  • If there are no free slots, acquire blocks the goroutine that called it.
  • Calling release frees up a previously taken slot.
  • If there are any goroutines blocked on acquire when release is called, one of them will immediately take the freed slot and unblock.

You can implement a simple semaphore with a buffered channel, where N is the channel's size. To acquire the semaphore, send a value into the channel. To release it, take a value from the channel:

// Try changing nConc and see how the elapsed time changes.
const nConc = 4
const nCalls = 100
sema := make(chan struct{}, nConc)

var wg sync.WaitGroup
for range nCalls {
    sema <- struct{}{}
    wg.Go(func() {
        defer func() { <-sema }()
        time.Sleep(time.Millisecond) // do some work
    })
}
wg.Wait()
elapsed: 25ms

For more complex situations, use the golang.org/x/sync/semaphore package.

Rendezvous

A rendezvous lets two goroutines wait for each other:

  • There are two goroutines — G1 and G2 — and each one can signal that it's ready.
  • If G1 signals but G2 hasn't yet, G1 blocks and waits.
  • If G2 signals but G1 hasn't yet, G2 blocks and waits.
  • When both have signaled, they both unblock and continue running.

You can implement a simple rendezvous with a wait group:

var rend sync.WaitGroup
rend.Add(2)

var wg sync.WaitGroup
wg.Go(func() {
    fmt.Println("before rendezvous")
    rend.Done()
    rend.Wait()
    fmt.Println("after rendezvous")
})
wg.Go(func() {
    fmt.Println("before rendezvous")
    rend.Done()
    rend.Wait()
    fmt.Println("after rendezvous")
})
wg.Wait()
before rendezvous
before rendezvous
after rendezvous
after rendezvous
Barrier

A barrier is a general case of a rendezvous. It lets N goroutines wait for each other:

  • The barrier has a counter (starting at 0) and a threshold N.
  • Each goroutine that reaches the barrier increases the counter by 1.
  • The barrier blocks any goroutine that reaches it.
  • Once the counter reaches N, the barrier unblocks all waiting goroutines.

You can implement a simple barrier with a wait group:

const n = 4
var bar sync.WaitGroup
bar.Add(n)

var wg sync.WaitGroup
for range n {
    wg.Go(func() {
        fmt.Println("before the barrier")
        bar.Done()
        bar.Wait()
        fmt.Println("after the barrier")
    })
}
wg.Wait()
before the barrier
before the barrier
before the barrier
before the barrier
after the barrier
after the barrier
after the barrier
after the barrier

# Signaling

The sync.Cond (conditional variable) type lets one goroutine signal to another that it's ready, and lets the other goroutine wait for that signal.

A Cond includes a mutex and has two methods — Wait and Signal.

  • Wait unlocks the mutex and suspends the goroutine until it receives a signal.
  • Signal wakes the goroutine that is waiting on Wait.
  • When Wait wakes up, it locks the mutex again.
cond := sync.NewCond(&sync.Mutex{})
done := false

var wg sync.WaitGroup
wg.Go(func() {
    cond.L.Lock()
    fmt.Println("G1 is ready to signal")
    done = true
    cond.Signal()
    cond.L.Unlock()
})
wg.Go(func() {
    cond.L.Lock()
    for !done {
        cond.Wait()
    }
    fmt.Println("G2 received the signal")
    cond.L.Unlock()
})
wg.Wait()
G1 is ready to signal
G2 received the signal

If there are multiple waiting goroutines when Signal is called, only one of them will be resumed. If there are no waiting goroutines, Signal does nothing.

You can also use the Broadcast method. While Signal wakes up only one goroutine waiting on Cond.Wait, the Broadcast method wakes up all such goroutines.

You can signal with a channel:

signal := make(chan struct{}, 1)

go func() {
    // do something
    signal <- struct{}{}
}()

go func() {
    <-signal
    // do something
}()

And broadcast too:

broadcast := make(chan struct{})

go func() {
    // do something
    close(broadcast)
}()

go func() {
    <-broadcast
    // do something
}()

go func() {
    <-broadcast
    // do something
}()

Broadcasting with a condition variable is limited: it only sends a signal, not the actual data, and it only works once. With channels, you can build a publish/subscribe system that doesn't have these limitations:

type Publisher struct {
    sbox []chan int // subscription channels
    mu   sync.Mutex // protects the state
}

func (p *Publisher) Subscribe() <-chan int {
    p.mu.Lock()
    defer p.mu.Unlock()
    sub := make(chan int, 1)
    p.sbox = append(p.sbox, sub)
    return sub
}

func (p *Publisher) Broadcast(v int) {
    p.mu.Lock()
    defer p.mu.Unlock()
    for _, sub := range p.sbox {
        select {
        case sub <- v:
        default:
        }
    }
}

# Run once

The sync.Once type makes sure that the given function runs only once. If multiple goroutines call Once.Do at the same time, only one will run the function, while the others will wait until it returns:

total := 0
initState := func() {
    total += 1
}

var once sync.Once

var wg sync.WaitGroup
wg.Go(func() {
    once.Do(initState)
    // do something
})
wg.Go(func() {
    once.Do(initState)
    // do something
})
wg.Wait()
total: 1

Once is perfect for one-time initialization or cleanup in a concurrent environment.

Besides the Once type, the sync package also includes three convenience once-functions:

// Calls f only once.
func (o *Once) Do(f func())

// Returns a function that calls f only once.
func OnceFunc(f func()) func()

// Returns a function that calls f only once
// and returns the value from that first call.
func OnceValue[T any](f func() T) func() T

// Returns a function that calls f only once
// and returns the pair of values from that first call.
func OnceValues[T1, T2 any](f func() (T1, T2)) func() (T1, T2)

# Object pool

The sync.Pool type helps reuse memory instead of allocating it every time, which reduces the load on the garbage collector:

pool := sync.Pool{
    New: func() any {
        buf := make([]byte, 1024)
        return &buf
    },
}

// Only allocates 4*1024 B, despite 4000 loop iterations.
var wg sync.WaitGroup
for range 4 {
    wg.Go(func() {
        for range 1000 {
            buf := pool.Get().(*[]byte)
            sink = buf
            pool.Put(buf)
        }
    })
}
wg.Wait()
Memory allocated: 4 KB

Get takes an item from the pool. If there are no available items, it creates a new one using New (which we have to define ourselves, since the pool doesn't know anything about the items it creates). Put returns an item back to the pool.

Things to keep in mind:

  • New should return a pointer, not a value, to reduce memory copying and avoid extra allocations.
  • The pool has no size limit. If you start 1000 more goroutines that all call Get at the same time, 1000 more buffers will be allocated.
  • After an item is returned to the pool with Put, you shouldn't use it anymore (since another goroutine might already have taken and started using it).

# Atomics

An operation without synchronization can only be truly atomic if it translates to a single processor instruction. Such operations don't need locks and won't cause issues when called concurrently (even the write operations).

There are only a few atomics, and they're all found in the sync/atomic package:

Int32     Bool
Int64     Value
Uint32    Pointer
Uint64

Each atomic type provides the following methods:

  • Load reads the value of a variable.
  • Store sets a new value.
  • Swap sets a new value (like Store) and returns the old one.
  • CompareAndSwap sets a new value only if the current value is still what you expect it to be.
var n atomic.Int32
n.Store(10)
swapped := n.CompareAndSwap(10, 42)
fmt.Println("CompareAndSwap 10 -> 42:", swapped)
fmt.Println("n =", n.Load())
CompareAndSwap 10 -> 42: true
n = 42

Numeric types also provide an Add method that increments the value by the specified amount.

All methods are either translated into a single CPU instruction or are otherwise guaranteed to be atomic, so they are safe to use from multiple goroutines.

The composition of atomics is always non-atomic:

var delta atomic.Int32
var counter atomic.Int32

func increment() {
    // Not atomic; causes a race condition.
    delta.Add(1)
    sleep(10)
    counter.Add(delta.Load())
}

// After 100 concurrent increments,
// the final value is NOT guaranteed.
counter = 9386

A bulletproof way to make a composite operation atomic and prevent race conditions is to use a mutex:

var delta int32
var counter int32
var mu sync.Mutex

func increment() {
    // Atomic; doesn't cause a race condition.
    mu.Lock()
    delta += 1
    sleep(10)
    counter += delta
    mu.Unlock()
}

// After 100 concurrent increments, the final value is guaranteed:
// counter = 1+2+...+100 = 5050
counter = 5050

Sometimes you can use an atomic type instead of a mutex to exit early:

type Gate struct {
    closed atomic.Bool
}

func (g *Gate) Close() {
    if !g.closed.CompareAndSwap(false, true) {
        return // ignore repeated calls
    }
    // The gate is closed.
    // We can free resources now.
}

# Testing

If your concurrent program uses channels or custom types with synchronization methods like Wait, you can use those in your tests. This way, your tests won't be much more complicated than if the code were synchronous:

// Calc calculates something asynchronously.
func Calc() <-chan int {
    out := make(chan int, 1)
    go func() {
        out <- 42
    }()
    return out
}
func Test(t *testing.T) {
    // Wait for the Calc goroutine to finish.
    got := <-Calc()
    if got != 42 {
        t.Errorf("got: %v; want: 42", got)
    }
}
PASS

If there aren't any suitable synchronization "handles" in the code you're testing, you can use the synctest package. It exports two functions:

func Test(t *testing.T, f func(*testing.T))
func Wait()

synctest.Test runs an isolated bubble. The bubble uses a fake clock, and you can manually control goroutine synchronization with synctest.Wait.

synctest.Wait blocks until all goroutines in the bubble — except the one that called Wait — have either finished or are durably blocked. This lets you wait for a specific goroutine to finish or get blocked, so you can check the program's state:

// NewProc starts the calculation.
func NewProc() *Proc {
    p := &Proc{done: make(chan struct{})}
    go func() {
        p.res = 42
        <-p.done // (X)
        p.res = 0
    }()
    return p
}
func Test(t *testing.T) {
    synctest.Test(t, func(t *testing.T) {
        p := NewProc()
        defer p.Stop()

        // Wait for the goroutine to block at point X.
        synctest.Wait()
        if got := p.Res(); got != 42 {
            t.Fatalf("got %v, want 42", got)
        }
    })
}
PASS

The fake clock in synctest.Test move forward only if: ➊ all goroutines in the bubble are durably blocked; ➋ there's a future moment when at least one goroutine will unblock; and ➌ synctest.Wait isn't running. Thanks to this, time-dependent tests run instantly:

// Calc processes a value from the input channel.
// Times out if no input is received after 3 seconds.
func Calc(in chan int) (int, error) {
    select {
    case v := <-in:
        return v * 2, nil
    case <-time.After(3 * time.Second):
        return 0, ErrTimeout
    }
}
func Test(t *testing.T) {
    synctest.Test(t, func(t *testing.T) {
        ch := make(chan int)
        got, err := Calc(ch) // runs instantly

        if err != ErrTimeout {
            t.Errorf("got: %v; want: %v", err, ErrTimeout)
        }
        if got != 0 {
            t.Errorf("got: %v; want: 0", got)
        }
    })
}
PASS

The following operations durably block a goroutine:

  • A blocking send or receive on a channel created within the bubble.
  • A blocking select statement where every case is a channel created within the bubble.
  • Calling Cond.Wait.
  • Calling WaitGroup.Wait if all WaitGroup.Add calls were made inside the bubble.
  • Calling time.Sleep.

Blocking on mutexes, I/O, or system calls is not considered durable, and the synctest bubble can't handle them.

# Scheduling

At the hardware level, CPU cores are responsible for running parallel tasks.

At the operating system level, a thread is the basic unit of execution. There are usually many more threads than CPU cores, so the operating system's scheduler decides which threads to run and which ones to pause.

At the Go runtime level, a goroutine is the basic unit of execution. The runtime scheduler runs a fixed number of OS threads, often one per CPU core. There can be many more goroutines than threads, so the scheduler decides which goroutines to run on the available threads and which ones to pause. The scheduler keeps switching between goroutines to make sure each one gets a turn to run on a thread, instead of waiting in line forever.

  CPU                  OS                   Go runtime
┌──────────┐  run on ┌──────────┐  run on ┌────────────┐
│ Cores    │ <────── │ Threads  │ <────── │ Goroutines │
└──────────┘         └──────────┘         └────────────┘

This is how Go handles concurrency.

Goroutine scheduler

The goroutine scheduler's job is to run M goroutines on N operating system threads, where M can be much larger than N. Here's a very simplified version of it's algorithm:

  • If there's a free thread, assign it a goroutine from the queue.
  • If a running goroutine gets blocked (for example, while reading from a channel), put it back in the queue and assign a different goroutine to the thread.
  • If a running goroutine gets stuck in a syscall, start a new thread to run other goroutines until the blocked goroutine finishes the syscall.
  • Check the running goroutines every 10 ms. Preempt long-running goroutines and return them to the queue to prevent starvation.
┌─────┐┌─────┐┌─────┐┌─────┐
│ G17 ││ G18 ││ G19 ││ G20 │                        queue
└─────┘└─────┘└─────┘└─────┘

┌─────┐      ┌─────┐      ┌─────┐      ┌─────┐
│ G15 │      │ G16 │      │ G13 │      │ G14 │      running
└─────┘      └─────┘      └─────┘      └─────┘
  │            │            │            │
┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
│ Thread E │ │ Thread F │ │ Thread C │ │ Thread D │
└──────────┘ └──────────┘ └──────────┘ └──────────┘

┌─────┐      ┌─────┐
│ G11 │      │ G12 │                                syscalls
└─────┘      └─────┘
  │            │
┌──────────┐ ┌──────────┐
│ Thread A │ │ Thread B │
└──────────┘ └──────────┘

The number of threads running Go code is controlled by the GOMAXPROCS environment variable or the runtime.GOMAXPROCS function.

A goroutine is a structure that starts out using about 2 KB of memory, mostly for its stack. The stack can grow if needed. Since goroutines are so lightweight, you can run tens of thousands or even hundreds of thousands of them on a small machine.

# Diagnostics

To troubleshoot concurrent programs in production, we use metrics, profiling, and tracing.

Metrics show how the Go runtime is performing, like how much heap memory it uses or how long garbage collection pauses take. Each metric has a unique name and a value, which can be a number or a histogram.

You can use the runtime/metrics package to get a complete list of metrics or check the values of specific ones:

samples := []metrics.Sample{
    {Name: "/sched/gomaxprocs:threads"},
    {Name: "/sched/goroutines:goroutines"},
}
metrics.Read(samples)

for _, s := range samples {
    fmt.Printf("%s: %v\n", s.Name, s.Value.Uint64())
}
/sched/gomaxprocs:threads: 8
/sched/goroutines:goroutines: 1

In practice, people rarely do this manually. Instead, all metrics are automatically exported using Prometheus or OpenTelemetry libraries.

Profiling helps you understand exactly what the program is doing, what resources it uses, and where in the code this happens. Go uses a sampling profiler that's suitable for production.

The most commonly used profiles are CPU, which shows how much processor time each function uses, and heap, which shows how much heap memory each function uses. Goroutine, block, and mutex profiles help identify problems related to concurrency.

The easiest way to add a profiler to your app is by using the net/http/pprof package. To collect a profile with the given name, call the /debug/pprof/{name} endpoint. To view the collected profile, use the go tool pprof utility:

go tool pprof -proto \
  "http://localhost:6060/debug/pprof/profile?seconds=N" > cpu.pprof
go tool pprof -http=localhost:8080 cpu.pprof

You can also profile manually:

// CPU profile.
file, _ := os.Create("cpu.prof")
defer file.Close()
pprof.StartCPUProfile(file)
defer pprof.StopCPUProfile()
// ...
// Any other profile.
file, _ := os.Create(name + ".prof")
defer file.Close()
pprof.Lookup(name).WriteTo(file, 0)

Tracing records certain types of events while the program is running, mainly those related to concurrency and memory. When the profiling server from the net/http/pprof package is running, call the /debug/pprof/trace endpoint to collect a trace. To view the results, use the go tool trace utility.

You can also collect a trace manually:

file, _ := os.Create("trace.out")
defer file.Close()
trace.Start(file)
defer trace.Stop()
// ...

You can set up automatic tracing with a sliding window that's limited by size or duration. This is called "flight recording". It lets you always keep a recent trace available in case something goes wrong:

cfg := trace.FlightRecorderConfig{
    MinAge:   5 * time.Second,
    MaxBytes: 3 << 20, // 3MB
}
rec := trace.NewFlightRecorder(cfg)
rec.Start()
defer rec.Stop()

# Final thoughts

We've covered a number of Go tools for writing concurrent programs:

  • Goroutines for running concurrent tasks.
  • Channels and select as flexible communication tools.
  • Timers and tickers for working with time.
  • Context for canceling operations.
  • Wait groups for synchronizing goroutines.
  • Mutexes to prevent race conditions.
  • Condition variables for signaling events.
  • Once for safe one-time initialization.
  • Pools to reduce garbage collector load.
  • Atomic operations.

If you like the book, please recommend it to your friends or colleagues. If you're interested, check out my other books and projects.

I'm glad you finished the book. Thank you, and I'll see you next time!

★ Subscribe to keep up with new posts.