Go語言併發程式設計:WaitGroup
阿新 • • 發佈:2021-10-19
我們知道,在併發程式設計中,主要執行緒需要等待子執行緒執行結束後才能退出,go語言中,主 goroutine 等待其他 goroutine 執行結束可以使用通道來解決,具體實現可以參考文章Go語言併發程式設計:互斥鎖中的例子。使用通道可能不是很簡潔,本文介紹另一種方法,也就是sync包中的WaitGroup型別來等待 goroutine執行完成。
sync.WaitGroup型別主要包括3個方法:
- Add:用於需要等待的 goroutine 的數量
- Done:對計數器的值進行減一操作,一般在需要等待的goroutine執行完成之前執行這一操作,可以通過defer語句呼叫它
- Wait:用於阻塞當前的 goroutine,直到其所屬值中的計數器歸零
下面直接修改Go語言併發程式設計:互斥鎖中的例子,使用WaitGroup來等待goroutine:
package main import ( "flag" "fmt" "sync" ) var ( mutex sync.Mutex balance int protecting uint // 是否加鎖 sign = make(chan struct{}, 10) //通道,用於等待所有goroutine ) var wg sync.WaitGroup // 存錢 func deposit(value int) { if protecting == 1 { mutex.Lock() defer mutex.Unlock() } fmt.Printf("餘額: %d\n", balance) balance += value fmt.Printf("存 %d 後的餘額: %d\n", value, balance) fmt.Println() wg.Done() } // 取錢 func withdraw(value int) { defer wg.Done() if protecting == 1 { mutex.Lock() defer mutex.Unlock() } fmt.Printf("餘額: %d\n", balance) balance -= value fmt.Printf("取 %d 後的餘額: %d\n", value, balance) fmt.Println() } func main() { wg.Add(10) for i:=0; i < 5; i++ { go withdraw(500) // 取500 go deposit(500) // 存500 } wg.Wait() fmt.Printf("當前餘額: %d\n", balance) } func init() { balance = 1000 // 初始賬戶餘額為1000 flag.UintVar(&protecting, "protecting", 1, "是否加鎖,0表示不加鎖,1表示加鎖") }
先聲明瞭一個WaitGroup型別的全域性變數wg。main方法中的wg.Add(10)表示有10個goroutine需要等待,wg.Wait()表示等待那10個goroutine執行結束。
另外,WaitGroup值是可以被複用的,wg歸0後,可以繼續使用:
func main() { wg.Add(5) for i:=0; i < 5; i++ { go deposit(500) // 存500 } wg.Wait() time.Sleep(time.Duration(3) * time.Second) wg.Add(5) for i:=0; i < 5; i++ { go withdraw(500) // 取500 } wg.Wait() fmt.Printf("當前餘額: %d\n", balance) }
如果你有多組任務,而這些任務需要序列執行,可以使用上面這種寫法。
比如實現按順序存錢:
func main() {
for i:=0; i < 5; i++ {
wg.Add(1)
go deposit(500+i) // 存500
wg.Wait()
}
fmt.Printf("當前餘額: %d\n", balance)
}
執行結果:
餘額: 1000
存 500 後的餘額: 1500
餘額: 1500
存 501 後的餘額: 2001
餘額: 2001
存 502 後的餘額: 2503
餘額: 2503
存 503 後的餘額: 3006
餘額: 3006
存 504 後的餘額: 3510
當前餘額: 3510