golang 的 sync.WaitGroup

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

WaitGroup的用途:它能夠一直等到所有的goroutine執行完成,並且阻塞主線程的執行,直到所有的goroutine執行完成。

官方對它的說明如下:

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.

 

sync.WaitGroup只有3個方法,Add(),Done(),Wait()。

其中Done()是Add(-1)的別名。簡單的來說,使用Add()添加計數,Done()減掉一個計數,計數不為0, 阻塞Wait()的運行。

 

例子代碼如下:

同時開三個協程去請求網頁, 等三個請求都完成後才繼續 Wait 之後的工作。

var wg sync.WaitGroup
var urls = []string{
    "http://www.golang.org/",
    "http://www.google.com/",
    "http://www.somestupidname.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()

 

或者下面的測試代碼

用於測試 給chan發送 1千萬次,並接受1千萬次的效能。

package main

import (
    "fmt"
    "sync"
    "time"
)

const (
    num = 10000000
)

func main() {
    TestFunc("testchan", TestChan)
}

func TestFunc(name string, f func()) {
    st := time.Now().UnixNano()
    f()
    fmt.Printf("task %s cost %d \r\n", name, (time.Now().UnixNano()-st)/int64(time.Millisecond))
}

func TestChan() {
    var wg sync.WaitGroup
    c := make(chan string)
    wg.Add(1)

    go func() {
        for _ = range c {
        }
        wg.Done()
    }()

    for i := 0; i < num; i++ {
        c <- "123"
    }

    close(c)
    wg.Wait()

}

參考:

http://www.liguosong.com/2014/05/06/golang-sync-waitgroup/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.