Sync - cruisechang/wiki-golang GitHub Wiki

WaitGroup

  • WaitGroup.Add() 增加或減少counter
  • WaitGroup.Wait() 開始等待
  • WaitGroup.Done() 完成/解除一個counter

WaitGroup 一個counter,需要一個done去解除。沒有解除就會一直等待。

Flow: Add(1) (改變counter)=> wait() (開始wait)=> Done() (結束本次counter) =>後續

Add()會改變Counter。但不能把Counter變負的,否則panic。

import (
    "sync"
)

func main() {

var wg sync.WaitGroup
var urls = []string{
        "http://www.golang.org/",
        "http://www.google.com/",
}
for _, url := range urls {
        // Increment the WaitGroup counter.
        wg.Add(1)
        // Launch a goroutine to fetch the URL.
        go func(url string) {
                // Decrement the counter when the goroutine completes.
                defer wg.Done()
                // Fetch the URL.
                http.Get(url)
        }(url)
}
// Wait for all HTTP fetches to complete.
wg.Wait()
}