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已经退出")
}

你可能感兴趣的:(Golang,Golang学习笔记)