Go並列筆記
等待组添加、等待组等待
func Afunction(num int) {
fmt.Println(num)
waitgroup.Done() //タスク一個終了、タスク数-1、実際.Doneは.Add(-1)
}
func main() {
for i := 0; i < 10; i++ {
waitgroup.Add(1) //goroutineごとで、タスク+1、(全体10なので、10回繰り返す)
go Afunction(i)
}
waitgroup.Wait() //.Wait()ここで待つ
}
他在图书馆学习了一整天。
func main() {
var wg sync.WaitGroup
wg.Add(3)
for i := 0; i < 3; i++ {
go func(i int) {
defer wg.Done()
fmt.Println("reading", i)
}(i)
}
fmt.Println("ready go")
wg.Wait()
}
不正确的写法:
func main() {
var wg sync.WaitGroup
for i := 0; i < 3; i++ {
wg.Add(1) //ここが違うだよ!
go func(i int) {
defer wg.Done()
fmt.Println("reading", i)
}(i)
}
fmt.Println("ready go")
wg.Wait()
}
//結果:
ready go
reading 0
reading 1
reading 2
第二个例子:
func main() {
var wg sync.WaitGroup
wg.Add(1)
go func() {
fmt.Println("wait1 enter")
wg.Wait()
fmt.Println("wait1 exit")
}()
go func() {
fmt.Println("wait2 enter")
wg.Wait()
fmt.Println("wait2 exit")
}()
go func() {
fmt.Println("wait3 enter")
wg.Wait()
fmt.Println("wait3 exit")
}()
go func() {
fmt.Println("done")
wg.Add(-1)
}()
wg.Wait()
time.Sleep(time.Second)
fmt.Println("main exit")
}
//出力1
wait3 enter
wait2 enter
wait1 enter
done
wait1 exit
wait3 exit
wait2 exit
//出力2
done
wait1 enter
wait1 exit
wait2 enter
wait2 exit
wait3 enter
wait3 exit
main exit