眺めて覚えるGo言語 その16 並列処理
「sync.WaitGroupは複数のgoroutineの完了を待つ」
thread.go
package main
import ("fmt";"sync";"time")
func main() {
wg := sync.WaitGroup{}
for i := 0; i < 10; i++ {
wg.Add(1)
go func (i int) {
defer wg.Done()
fmt.Println("Thread no",i)
time.Sleep(1)
}(i)
}
wg.Wait()
fmt.Println("complete!")
}
実行結果
>go run thread.go
Thread no 0
Thread no 5
Thread no 2
Thread no 3
Thread no 9
Thread no 4
Thread no 6
Thread no 7
Thread no 8
Thread no 1
complete!