Trung BìnhGolang iconGolang

WaitGroup dùng khi nào?

Dùng khi cần đợi nhiều goroutines hoàn thành trước khi tiếp tục.

Đơn giản hơn channel cho fan-out/fan-in.

go
var wg sync.WaitGroup

urls := []string{"https://a.com", "https://b.com", "https://c.com"}

for _, url := range urls {
    wg.Add(1) // đăng ký 1 goroutine
    go func(u string) {
        defer wg.Done() // báo hoàn thành khi return
        fetch(u)
    }(url)
}

wg.Wait() // block đến khi tất cả goroutines Done
fmt.Println("all done")

wg.Add(n) đăng ký n goroutines. wg.Done() thường dùng kết hợp defer.

Xem toàn bộ Golang cùng filter theo level & chủ đề con.

Mở danh sách Golang