1. 程式人生 > >《Go語言實戰》筆記之協程同步 sync.WaitGroup

《Go語言實戰》筆記之協程同步 sync.WaitGroup

調用 lec run cti not collect cal 筆記 channel

原文地址(歡迎互換友鏈):

http://www.niu12.com/article/8

<p>文檔介紹</p>
<code>
// A WaitGroup waits for a collection of goroutines to finish.
// The main goroutine calls Add to set the number of
// goroutines to wait for. Then each of the goroutines
// runs and calls Done when finished. At the same time,
// Wait can be used to block until all goroutines have finished.
//
// A WaitGroup must not be copied after first use.
翻譯
一個WaitGroup等待一個goroutines集合的完成,
main(goroutines)調用Add()方法設置需要等到的goroutine熟練
然後執行每一個goroutine,並且完成時調用Done()方法
與此同時,Wait()方法可以用來鎖住main(goroutines)直到所有goroutine完成

首次使用後不得復制WaitGroup
</code>

<p>實例代碼</p>
<code>
package main

import (
"fmt"
"sync"
)
var wg sync.WaitGroup

func printerOne(ch chan int) {
for i := range ch{
fmt.Printf("printerOne: %v\n" , i)
}
// 申明當前goroutine完成
wg.Done()
}

func printerTwo(ch chan int) {
for i := range ch{
fmt.Printf("printerTwo: %v\n" , i)

}
// 申明當前goroutine完成
wg.Done()
}

func main() {
// 申明一個channel c
c := make(chan int)

// 申明有兩個goroutine需要執行
wg.Add(2)

// 執行goroutine
go printerOne(c)
go printerTwo(c)

// 向channel c發送數據
for i:=0; i < 10; i++ {
c <- i
}
// 關閉channel c
close(c)
// 等待goroutine全部完成
wg.Wait()
}
</code>

《Go語言實戰》筆記之協程同步 sync.WaitGroup