35

Go语言sync库和WaitGroup的使用

 5 years ago
source link: https://studygolang.com/articles/15298?amp%3Butm_medium=referral
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.
// code_041_sync_WaitGroup project main.go
package main

import (
    "fmt"
    "sync"
)

func main() {
    fmt.Println("Hello World!")
    var wg sync.WaitGroup
    wg.Add(2)
    go func() {
        defer wg.Done()
        for i := 0; i < 10000; i++ {
            fmt.Printf("Hello,Go.This is %d\n", i)
        }
    }()
    go func() {
        defer wg.Done()
        for i := 0; i < 10000; i++ {
            fmt.Printf("Hello, world.This is %d\n", i)
        }
    }()
    wg.Wait()
}

sync.WaitGroup是一个计数的信号量,使main函数所在主线程等待两个goroutine执行完成后再结束,否则两个goroutine还在运行时,主线程已经结束。

sync.WaitGroup使用非常简单,使用Add方法设设置计数器为2,每一个goroutine的函数执行完后,调用Done方法减1。Wait方法表示如果计数器大于0,就会阻塞,main函数会一直等待2个goroutine完成再结束。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK