Go并发控制之sync.WaitGroup

    WaitGroup 会将main goroutine阻塞直到全部的goroutine运行结束,从而达到并发控制的目的。使用方法很是简单,真心佩服创造Golang的大师们!golang

 

type WaitGroup               //至关于一个箱子,将main goroutine 保护到里面

func (*WaitGroup) Add   //调用一次为箱子加一把锁(固然,你愿意也能够多把)

func (*WaitGroup) Done  // 调用一次开一把锁(only one!) 

func (*WaitGroup) Wait    //箱子的盖子,没锁了自动打开

 

官网说明:一个WaitGroup锁等待一个goroutines合集结束。main goroutine里面调用Add方法设置须要等待的goroutines 数量,而后运行每个goroutine,而且当其结束时调用Done方法。同时,main goroutine 被锁住直到全部的goroutines完成。并发

使用方法(官网Example):fetch

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()

 

任何放在wg.Wait() 后面的语句阻塞,直到全部的goroutine返回:google

package main

import (
        "fmt"
        "net/http"
        "sync"
)

func main() {
        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)
                        fmt.Println("我先干活, 主程序等着我")
                }(url)
        }
        // Wait for all HTTP fetches to complete.
        wg.Wait()
        fmt.Println("应该最后才出来")

}
相关文章
相关标签/搜索