imu-note
imu-note
いむたろ
いむたろ
@imutaroh
新卒エンジニア / データ基盤 × AI
search
view
notes
status: growing作成 2026-10-29更新 2026-10-29
目次 · 9

🚧 理解中

goroutine

go は始めさせるだけ。待たない。

go fmt.Println("orders")
go fmt.Println("users")
fmt.Println("done")
// → done(main が先に終わると、goroutine も消える)

待つ

var wg sync.WaitGroup
wg.Go(func() { fmt.Println("orders") })
wg.Go(func() { fmt.Println("users") })
wg.Wait() // 全部終わるまで止まる
fmt.Println("done")
// → users orders done(順番は決まらない)

途中でやめる

ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()

err := fetch(ctx)                         // 3秒かかる API
fmt.Println(err)                          // → context deadline exceeded(1秒で抜けた)
errors.Is(err, context.DeadlineExceeded) // → true

受け取った側が ctx.Done() を見ないと効かない。

func fetch(ctx context.Context) error {
	time.Sleep(3 * time.Second) // ✕ ctx を見ていない → 3秒待たされる
	return nil
}

http.NewRequestWithContext(ctx, "GET", url, nil) // ○ 標準ライブラリが中で見てくれる
db.QueryContext(ctx, "SELECT ...")               // ○
usecase(context.Background()) // ✕ 鎖が切れる。ブラウザを閉じても DB クエリは止まらない
usecase(ctx)                  // ○ 受け取った ctx をそのまま渡す

同時に触らせない

count := 0
for range 1000 {
	wg.Go(func() { count++ }) // ✕ 読む→足す→書くの途中で割り込まれる
}
wg.Wait()
// → 973、986、956…(毎回違う)
var mu sync.Mutex
for range 1000 {
	wg.Go(func() {
		mu.Lock()
		defer mu.Unlock() // どの return でも必ず返す
		count++
	})
}
wg.Wait()
// → 1000
go run -race main.go # → WARNING: DATA RACE

数を絞る

sem := make(chan struct{}, 3) // 3個まで入る
for _, s := range shops {
	wg.Go(func() {
		sem <- struct{}{}        // 入れる。満杯なら待つ
		defer func() { <-sem }() // 終わったら取り出す
		fetchOrders(url, s)
	})
}
wg.Wait()

同時に4件以上で 429 を返す API に、30店舗を取りに行った結果:

時間失敗
1店舗ずつ6.0秒0件
全部同時0.2秒27件
3つまで2.0秒0件

チャネル

ch := make(chan int, 2) // int を運ぶ。2個まで入る
ch <- 10                // 入れる。満杯なら待つ
v := <-ch               // 取り出す。空なら待つ
<-ch                    // 取り出して捨てる

待つ上限

<-res は届くまで止まる。上限は select で付ける。

for range shops {
	select {
	case r := <-res: // 先に結果が届いた
		fmt.Println("got shop", r.shop)
	case <-ctx.Done(): // 先に1秒たった
		fmt.Println("give up:", ctx.Err())
		return
	}
}
// 店舗2だけ固まっている API → ✕ <-res だけ:5.2秒 / ○ select:1.0秒

go を見たら聞くこと

  • 誰がどこで待つ?
  • いつまで待つ?
  • 同じ変数を書き換えていない?

関連