Go のゴルーチンとチャネル: 逐次プロセスの通信による実用的な同時実行性
Go は逐次プロセスの通信を実装します: 超軽量ゴルーチン、パイプとしてのチャネル 安全な通信のために typed、多重化のために select、同期のために WaitGroup、 伝播された削除の context.Context — ほとんどの場合、明示的なミューテックスなし ケースの。
Go CSP モデル
抱きしめて行きなさい 順次プロセスの通信 (CSP)、正式なモデル 1978 年に Tony Hoare によって提案されました。 基本原則: 複数のゴルーチンを使用する代わりに 同じ変数 (ミューテックスを使用) の読み取りと書き込みを行うゴルーチンは、 チャネル — データの所有権を転送する型付きパイプ。
Go ランタイムは、OS スレッドのプール上の goroutine のスケジューリングを管理します (デフォルトでは、
利用可能なコアの数に応じて制御されます GOMAXPROCS)。ゴルーチンとは、
ブロック操作 (I/O、チャネル受信) 中に自動的に一時停止され、他の操作は許可されます。
先に進むゴルーチン。
Goroutine: 構造とライフサイクル
package main
import (
"fmt"
"time"
)
func worker(id int, done chan struct{}) {
fmt.Printf("Worker %d started\n", id)
time.Sleep(100 * time.Millisecond) // simula lavoro
fmt.Printf("Worker %d finished\n", id)
done <- struct{}{} // segnala completamento
}
func main() {
done := make(chan struct{}, 5) // channel bufferizzato per 5
// Lancia 5 goroutine concorrentemente
for i := 0; i < 5; i++ {
go worker(i, done) // "go" avvia la goroutine
}
// Aspetta che tutte completino
for i := 0; i < 5; i++ {
<-done // riceve dal channel (blocca se vuoto)
}
fmt.Println("All workers done")
}
// Costo di una goroutine: ~2-8KB stack (cresce dinamicamente fino a 1GB)
// vs ~1MB per un OS thread
// Go può avere milioni di goroutine attive contemporaneamente
チャネル: タイプとパターン
バッファなしおよびバッファありのチャネル
// Channel unbuffered: sincronizzazione diretta
// Send blocca finché un receiver è pronto
ch := make(chan int) // unbuffered
go func() { ch <- 42 }() // blocca finché qualcuno riceve
v := <-ch // sblocca il sender
// Channel buffered: coda FIFO con capacità fissata
// Send blocca SOLO se il buffer è pieno
buffered := make(chan int, 10) // buffer da 10 elementi
buffered <- 1 // non blocca (buffer ha spazio)
buffered <- 2 // non blocca
v := <-buffered // riceve 1 (FIFO)
// Directional channel types: sicurezza a compile time
func producer(ch chan<- int) { // solo write
ch <- 42
}
func consumer(ch <-chan int) { // solo read
v := <-ch
fmt.Println(v)
}
パターン: パイプライン
// Pipeline: catena di goroutine connesse da channel
// Ogni fase legge dall'input channel e scrive sull'output channel
func generate(nums ...int) <-chan int {
out := make(chan int)
go func() {
for _, n := range nums {
out <- n
}
close(out) // IMPORTANTE: chiudi quando finisci
}()
return out
}
func square(in <-chan int) <-chan int {
out := make(chan int)
go func() {
for n := range in { // range su channel riceve finché chiuso
out <- n * n
}
close(out)
}()
return out
}
func main() {
// Compone la pipeline
c := generate(2, 3, 4, 5)
out := square(c)
// Consuma l'output
for v := range out {
fmt.Println(v) // 4, 9, 16, 25
}
}
選択: 複数のチャネルでの多重化
select は囲碁の競争において最も強力なキーワードです: 待ってください
複数のチャネルを同時に処理し、チャネル準備完了ケースを実行します。複数チャンネルの場合
準備ができているので、彼はランダムに選択します。
// Timeout pattern con select
import "time"
func fetchWithTimeout(url string, timeout time.Duration) (string, error) {
resultCh := make(chan string, 1)
errCh := make(chan error, 1)
go func() {
result, err := fetch(url)
if err != nil {
errCh <- err
return
}
resultCh <- result
}()
select {
case result := <-resultCh:
return result, nil
case err := <-errCh:
return "", err
case <-time.After(timeout):
return "", fmt.Errorf("timeout after %v", timeout)
}
}
// Fan-out/fan-in con select e done channel
func merge(channels ...<-chan int) <-chan int {
merged := make(chan int)
var wg sync.WaitGroup
multiplex := func(ch <-chan int) {
defer wg.Done()
for v := range ch {
merged <- v
}
}
wg.Add(len(channels))
for _, ch := range channels {
go multiplex(ch)
}
go func() {
wg.Wait()
close(merged)
}()
return merged
}
context.Context: 伝播された消去
パッケージ context 削除を伝播するための Go の標準メカニズムです
ゴルーチンのチェーンを介して。 I/O または長時間の作業を行う関数はこれを受け入れる必要があります。
ある context.Context 最初のパラメータとして:
import (
"context"
"fmt"
"time"
)
// Funzione che rispetta la cancellazione
func longOperation(ctx context.Context, id int) error {
for i := 0; i < 10; i++ {
select {
case <-ctx.Done(): // controlla se il context è cancellato
return ctx.Err() // errore: context.Canceled o DeadlineExceeded
default:
fmt.Printf("Step %d/%d\n", i+1, 10)
time.Sleep(100 * time.Millisecond)
}
}
return nil
}
func main() {
// Context con timeout di 500ms
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel() // SEMPRE defer cancel() per liberare le risorse
err := longOperation(ctx, 1)
if err != nil {
fmt.Printf("Cancelled: %v\n", err) // context deadline exceeded
}
}
// Context si propaga attraverso le chiamate:
// Handler HTTP -> Service -> Repository -> Database
// Se il client disconnette, il context si cancella e risale tutta la catena
WaitGroup: 同期パターン
import "sync"
func processAll(items []Item) {
var wg sync.WaitGroup
results := make([]Result, len(items))
for i, item := range items {
wg.Add(1)
go func(i int, item Item) { // passa i e item come parametri!
defer wg.Done()
results[i] = process(item) // scrivere indici diversi è safe
}(i, item)
}
wg.Wait() // blocca finché tutti Done() sono stati chiamati
fmt.Println(results)
}
// ERRORE COMUNE: closure su variabile del loop (prima di Go 1.22)
// In Go 1.22+ il loop variable è scoped per iterazione -- no problema
for _, item := range items {
go func() {
process(item) // Go 1.22+: safe. Go <1.22: BUG! usa go func(i Item) invece
}()
}
Race Detector: レース データの検索
// Compila ed esegui con il race detector integrato
go run -race main.go
go test -race ./...
// Esempio di data race che il detector trova:
var counter int
func increment() {
counter++ // DATA RACE! lettura + scrittura non atomica
}
// go run -race stamperà:
// WARNING: DATA RACE
// Write at 0x... by goroutine 6:
// main.increment()
// Previous write at 0x... by goroutine 5:
// main.increment()
// Fix con atomic o mutex:
import "sync/atomic"
var atomicCounter int64
atomic.AddInt64(&atomicCounter, 1) // atomico, thread-safe
Goroutine リーク: Go で最も一般的なバグ
受信チャネルでスタックする (誰も送信しない) か、受信しない goroutine
コンテキストを決して削除しないと、Goroutine リークが発生します。メモリと CPU を蓄積します。常に使用する
context 長時間の操作の場合は、各チャネルに送信者があることを確認してください。
または、明示的なクリーンアップを備えたバッファリングされたチャネルを使用します。
結論
Go の同時実行モデルは、バックエンド サービスにとって最も効果的なものの 1 つです: goroutine
超軽量、設計により競合状態を防ぐチャネル、 select 多重化用
e context 伝播キャンセルの場合。競合する Go コードのほとんど
明示的なミューテックスは必要ありません。
次の記事は Python に進みます。 asyncio.TaskGroup そして構造化された競争 Python 3.11+ では、Go の CSP に匹敵するセマンティック安全性がついに世界に提供されます 非同期/待機。







