Golang::WaitGroup 等待所有goroutine退出

前端之家收集整理的这篇文章主要介绍了Golang::WaitGroup 等待所有goroutine退出前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

简介

waitgroup类似于的信号量,用于等待所有的goroutine退出,基本的操作包括
add(int) 增加信号的值,add的参数应该都为正数 ,done() 减少信号的值,相当于add(-1) ,wait() 等待信号量值为0,等待期间会一直阻塞

code

package main

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

var waitGroutp = sync.WaitGroup{}

func goroutine1() {

    time.Sleep(time.Second * 3)
    waitGroutp.Done()
    fmt.Println("goroutine1退出")
}

func goroutine2() {
    time.Sleep(time.Second * 8)
    waitGroutp.Done()
    fmt.Println("goroutine2退出")
}

func goroutine3() {

    time.Sleep(time.Second * 1)
    waitGroutp.Done()
    fmt.Println("goroutine3退出")
}

func goroutine4() {

    time.Sleep(time.Second * 2)
    waitGroutp.Done()
    fmt.Println("goroutine4退出")
}

func main() {
    fmt.Println("waitgroup测试")

    go goroutine1()
    go goroutine2()
    go goroutine3()
    go goroutine4()

    waitGroutp.Add(4)
    //waitGroutp.Add(5) //add 大于开goroutie数目会死锁,
    //waitGroutp.Add(2) //少了会panic sync: negative WaitGroup counter
    waitGroutp.Wait()

    time.Sleep(time.Second * 2)

    fmt.Println("所有goroutine已经退出")
}
原文链接:https://www.f2er.com/go/187082.html

猜你在找的Go相关文章