CodeGym /コース /Go SELF /Bounded concurrency: buffered channel によるセマフォ in Go 1.25

Bounded concurrency: buffered channel によるセマフォ in Go 1.25

Go SELF
レベル 69, レッスン 1
使用可能

1. buffered channel 上のセマフォ: 理論と基本パターン

初心者の直感はとても説得力があります。「タスクが 10,000 個ある? なら 10,000 個の goroutine を起動すればいい!」小さな例ではこれでも動くので、頭は思わず “これでよし” と結論づけてしまいます。しかし実コードでは、このやり方は競争的な版の “みんなにピザを注文して、支払いはあとで考える” に変わります。

問題は Go が “たくさんの goroutine を扱えない” ことではありません。扱えます。問題は、システムを 管理しなくなる ことです。つまり、同時にいくつのタスクが実行されているのか、どれだけメモリを消費しているのか、誰が誰をブロックしているのか、そして「空中」にあるアクティブな操作が全部でいくつあるのか、が見えなくなります。

ここで登場するのが bounded concurrency、つまり制限された(制御された)並行性です。例えば「同時に 8 タスクまで」と明示的に上限を決めます。

2 つの制限: in-flight とキュー

初心者がよく混同する 2 つの数を、頭の中で分けておくのはとても有用です。

1 つ目は “実行中” の並列度 (in-flight): 今まさに実行されているタスク数です。

2 つ目は キューサイズ: システムが producer を止める前に、どれだけタスクを溜めてよいかです。

ここでは 1 つ目に集中します。つまり 同時実行数 を制限するのです。これが狭義の bounded concurrency であり、タスクが 100 万個あっても「同時に N 個まで」にします。

図式的には(簡略化すると)こんなイメージです:

flowchart LR
    P[Producer: creates tasks] -->|start| G[Task goroutines]
    G --> W[Work]
    W --> D[Done]
    subgraph Limit[Limit N]
      W
    end

必要なのは、W の領域へタスクを通す「ゲート」で、しかも上限 N に空きがあるときだけ通す仕組みです。

buffered channel 上のセマフォ: 「トークン」のアイデアと、それが Go らしい理由

“セマフォ” という言葉は OS の教科書っぽく聞こえるかもしれませんが、Go では普通とてもシンプルで実用的な手法です。バッファ付きチャネル を N 容量で作り、それを「許可」のカウンタとして使います。許可があればタスクは仕事を始められます。なければ待ちます。

典型的な形:

sem := make(chan struct{}, N)

なぜ struct{} なのか? データを運ぶ必要がなく、必要なのは「使用中/空き」の事実だけだからです。空の構造体はフィールド用のメモリを持たず(いわば「実質ゼロの荷物」)、コードの意味も明快です。「意味ではなく、トークンを送っている」のです。

セマフォの 2 つの操作:

  • acquire (スロットを取る) — sem <- struct{}{}
  • release (スロットを解放する) — <-sem

このとき、チャネルを「データ用のパイプ」ではなく「制御用の構造」として使っているわけですが、それで問題ありません。Go のチャネルは値の受け渡しだけでなく同期にも使え、標準的なパターンでもそれが積極的に活用されています。

最小スケルトン: 制限 + WaitGroup

道具の役割を混同しないことが重要です。セマフォは 同時に何タスクが実行されるか を制限しますが、全部が終わった瞬間を教えてはくれません。「全タスクの終了を待つ」には WaitGroup が必要です。

スケルトンはこうなります。タスクを起動し、それぞれがトークンを取り、仕事をし、トークンを返し、wg.Done() を呼びます。

package main

import (
	"fmt"
	"sync"
)

func main() {
	const limit = 3
	sem := make(chan struct{}, limit)

	var wg sync.WaitGroup
	for i := 1; i <= 5; i++ {
		wg.Add(1)
		sem <- struct{}{} // acquire: if the limit is reached, main waits

		go func(id int) {
			defer wg.Done()
			defer func() { <-sem }() // release

			fmt.Println("task", id, "done")
		}(i)
	}

	wg.Wait()
	fmt.Println("all done")
}

ここで 2 点に注目してください。

1 つ目は、sem <- struct{}{} が go ... の 前 にあることです。これは重要な設計選択で、あとで詳しく見ます。

2 つ目は、セマフォの解放を defer で書いていることです。こうしておけば、早い return があっても(あるいは、もしエラーがあっても) スロットが “漏れる” ことはありません。

acquire をどこで行うか: goroutine の前か、内部か

セマフォには 2 通りの使い方があり、どちらも “動きます” が、メモリ面と制御性の面で挙動が異なります。

方法 A: goroutine を起動する前に acquire する。

producer 側(多くは main や、処理を開始する関数)で acquire すると、余計な goroutine を作りません。上限に達したら、現在のスレッドは誰かがスロットを解放するまで待つだけです。

sem <- struct{}{} // acquire
wg.Add(1)
go func() {
	defer wg.Done()
	defer func() { <-sem }() // release
	// work
}()

つまり、「同時実行数」だけでなく、「作成される goroutine 数」も制限するということです。大量のタスクを扱うなら、たいていこちらの方が扱いやすいです。

方法 B: goroutine の内部で acquire する。

この方法では、各タスクごとに goroutine を作成し、その中でトークンを待ちます。同時実行数は制限されますが、goroutine は何千個も生成され、セマフォの前でただ待つことになります。

wg.Add(1)
go func() {
	defer wg.Done()

	sem <- struct{}{}         // acquire (now the goroutine waits)
	defer func() { <-sem }()  // release
	// work
}()

なぜこれは良くないことがあるのでしょうか。goroutine は軽量でも、無料ではないからです。そして何より、制御の一部を再び失います。つまり、「実行中」は制限しましたが、「全部で何個起動して待っているか」は制限していません。

実用的なルール(極端になりすぎない範囲で): タスク数が潜在的に多く、システムを本当に手綱で引いておきたいなら、acquire は go の前 に置いてください。

例: 結果付きのタスクバッチ処理

例を単なる “文字列を出力するだけ” にしないため、worker pool の流れを続けます。Task があり、Result を受け取りたいとします。ただしここでは常駐ワーカーは持たず、タスクごとに goroutine を起動しつつ、セマフォで並列度を制限します。

簡単なモデルにしましょう。タスクは数値を 2 倍し、その結果を結果チャネルへ流します。収集(collector) は main の 1 goroutine で行い、共有スライス上のレースを避けます。

package main

import (
	"fmt"
	"sync"
)

type Task struct {
	ID int
	N  int
}

type Result struct {
	ID  int
	Out int
}

func main() {
	tasks := []Task{{1, 10}, {2, 20}, {3, 30}, {4, 40}, {5, 50}}

	const limit = 2
	sem := make(chan struct{}, limit)
	results := make(chan Result)

	var wg sync.WaitGroup
	for _, t := range tasks {
		sem <- struct{}{} // acquire: limit in-flight
		wg.Add(1)

		go func(task Task) {
			defer wg.Done()
			defer func() { <-sem }() // release

			results <- Result{ID: task.ID, Out: task.N * 2}
		}(t)
	}

	go func() {
		wg.Wait()
		close(results)
	}()

	for r := range results {
		fmt.Println(r.ID, r.Out)
	}
}

ここには大事な点があります。「健康のために」task Task を匿名関数の引数として渡しています。これは、ループ変数に関する古典的な落とし穴から守ってくれます。

Go 1.22+ では典型的な range の問題は以前ほど厄介ではありませんが、それでも「必要な値を引数で渡す」習慣は、実際の変種でも役立ちます(たとえば、変数がループの外で宣言されている場合や、別のループを使う場合など)。夜中にデバッグするより、退屈なくらい正しい方がずっと良いのです。

セマフォと worker pool: 同じものではない

外から見ると、「どちらも並列度を制限しているだけでは? 何が違うの?」と思うかもしれません。違いは形と、何を “主要な構造” とみなすかです。

Worker pool は「タスクキュー + 長生きする固定数のワーカー」というアーキテクチャです。セマフォ方式は「タスクごとに goroutine を起動するが、同時に N 個まで」という考え方です。

エンジニアリング上の選択として比較するとわかりやすいです:

Criterion Worker pool Buffered-channel semaphore
Goroutine lifecycle Long-lived workers Usually one goroutine per task
Concurrency control Via number of workers Via the buffer size of sem
Task queue Usually a jobs channel Can be no queue at all (for example, a slice loop)
When it is easier to read When there is a task stream and producer/worker/collector roles When tasks are easier to think of as functions, but a limit is needed
Main beginner risk Closing results incorrectly and hanging Accumulating goroutines if acquire is inside go

In other words, a semaphore is an excellent tool when a worker pool feels structurally too heavy (too many roles), but parallelism must be limited anyway.

How to tell that the semaphore works: a thought experiment

To write concurrent code confidently, it helps to be able to “replay” it in your head. Imagine that limit = 2, and you have 5 tasks.

The first two loop iterations send two tokens into sem and start two goroutines. On the third iteration, sem <- struct{}{} tries to put in a third token, but the buffer is full, so the send blocks. And that is good: the producer stops and waits until one of the tasks releases a slot (<-sem). As soon as one task finishes and releases its token, the producer continues launching the next one.

Thus, the number of tasks “in flight” at any moment never exceeds cap(sem).

You can even print len(sem) temporarily for understanding — but remember that this is diagnostics, not control logic. In concurrent code, you cannot use “if len(sem) < cap(sem) then …” as the basis of a protocol: between the check and the action, everything may already have changed.

3. Typical mistakes when using a semaphore on a buffered channel

Mistake #1: making sem unbuffered and wondering why everything froze.
If you write make(chan struct{}), that is a channel without a buffer, and sem <- struct{}{} will wait for someone to do <-sem at the same time. That is no longer a semaphore, but a strange “passing a token hand to hand”. For a semaphore, you almost always need a buffered channel: make(chan struct{}, N).

Mistake #2: forgetting release and “plugging up” the system.
The most common failure: the slot is taken, but nobody remembers to free it. As a result, after some time the producer will permanently hit the full sem, and the program will “work forever” (that is, wait). The cure is discipline: write the release with defer func(){ <-sem }() next to acquire so that they are visually a pair.

Mistake #3: releasing twice and getting a hang at an unexpected moment.
A semaphore is strict bookkeeping: one acquire = one release. If you accidentally do two <-sem operations, the second one will wait for a token that nobody will ever send, and your task will hang instead. This is the case where the “error is silent” (no panic) and quietly turns the program into a statue.

Mistake #4: doing acquire inside a goroutine for a huge number of tasks and not understanding where the memory went.
Parallelism really will be limited, but goroutines will be created by the thousands and sit in the queue on sem <- struct{}{}. With small examples everything looks nice, but at scale — suddenly, “why are there so many goroutines?” If there can be many tasks, it is often safer to do acquire before go, so the producer itself slows down goroutine creation.

Mistake #5: accidentally capturing the loop variable and processing “the wrong data”.
If you launch a goroutine inside a loop, fix the value carefully. A reliable way is to pass the parameter into the anonymous function: go func(t Task){ ... }(t). Then the code reads and behaves the same no matter whether it is range or another loop.

1
タスク
Go SELF, レベル 69, レッスン 1
ロック未解除
セマフォキュー
セマフォキュー
1
タスク
Go SELF, レベル 69, レッスン 1
ロック未解除
合計ブースト
合計ブースト
1
タスク
Go SELF, レベル 69, レッスン 1
ロック未解除
最大公約数のペア
最大公約数のペア
1
タスク
Go SELF, レベル 69, レッスン 1
ロック未解除
ルーンパスポート
ルーンパスポート
コメント
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION