Go の並行処理

Goroutines and sync.WaitGroup

Start lightweight threads with the go keyword and wait for all of them to finish.

  • 上級
  • 約3分で読めます
  • 実行できるサンプル 1 件
学べること
  • The go keyword
  • WaitGroup: Add, Done, Wait
  • Writing results safely
Five goroutines
  1. 1wg.Add(1)count one more
  2. 2go square(...)runs on its own
  3. 3wg.Done()finished
  4. 4wg.Wait()main continues

Work that runs at the same time

A goroutine is a function that runs at the same time as the rest of the program. Writing go before a call starts one. Goroutines are cheap, so a program can run thousands of them.

main does not wait for goroutines by itself, so a WaitGroup counts them: Add before starting, Done when one finishes and Wait to block until the count is zero. Each goroutine writes to its own position of results, so the output is always the same.

重要なポイント

  1. go f() starts f in a new goroutine.
  2. main does not wait by itself.
  3. wg.Wait blocks until every Done is called.

実行できる Go のサンプル

Go
コードを実行 →
main.go
package main

import (
	"fmt"
	"sync"
)

func square(id int, results []int, wg *sync.WaitGroup) {
	defer wg.Done()
	results[id] = id * id
}

func main() {
	var wg sync.WaitGroup
	results := make([]int, 5)

	for id := 0; id < 5; id++ {
		wg.Add(1)
		go square(id, results, &wg)
	}

	wg.Wait() // block until every goroutine calls Done
	fmt.Println(results)
}
この例の実行ボタンを作成 実行結果
[0 1 4 9 16]

練習

サンプルをオンラインコンパイラーで開き、値を変えたり行を追加したりして、実行する前に出力を予想してみましょう。次に、わざとコードを壊してコンパイラーのメッセージを読んでみてください。

このレッスンを終えましたか?

学習済みにすると進み具合を記録できます。

次へ: Channels →

チャレンジで練習する

このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。

すべてのチャレンジ