44

golang之sync包之WaitGroup

 3 years ago
source link: https://www.80shihua.com/archives/2629
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

sync包

sync是synchronization同步这个词的缩写,所以也会叫做同步包。这里提供了基本同步的操作,比如互斥锁等等。这里除了Once和WaitGroup类型之外,大多数类型都是供低级库例程使用的。更高级别的同步最好通过channel通道和communication通信来完成。

WaitGroup

同步等待组,在类型上,它是一个结构体。一个WaitGroup的用途是等待一个goroutine的集合执行完成。主goroutine调用了Add()方法来设置要等待的goroutine的数量。然后,每个goroutine都会执行并且执行完成后调用Done()这个方法。与此同时,可以使用Wait()方法来阻塞,直到所有的goroutine都执行完成。

Add & Done & Wait

通过add设置需要同步等待的goroutine的数量,所有goroutine执行完成之后,调用Done方法来进行继续执行,其中wait用来等待goroutine的执行完毕,如果没有,则一直等待。

示例代码

package main
import(
      "fmt",
    "sync"
)

func main() {
    sayHello := func(wg *sync.WaitGroup, id int) {
        defer wg.Done()
        fmt.Printf("%v goroutine start ...\n", id)
        time.Sleep(2)
        fmt.Printf("%v goroutine exit ...\n", id)
    }

    var wg sync.WaitGroup
    const N = 5
    wg.Add(N)
    for i := 0; i < N; i++ {
        go sayHello(&wg, i)
    }

    fmt.Println("waiting for all goroutine ")
    wg.Wait()
    fmt.Println("All goroutines finished!")
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK