使用waitgroup同步goroutine

package main

import (
    "fmt"
    "sync"
)

func main() {
    wg := sync.WaitGroup{}

    //通过这里可以看出for循环的优先级高于wg.wait()执行的优先级
    for i:=0;i<8;i++{
        //在这里添加一个协成
        wg.Add(1)  //如果执行两个goroutine这里应该为wg.Add(2)
        go func(i int) {
            //这里协成操作完成
            defer wg.Done() //每次执行完成后进入下一次循环 继续刚才的操作直到循环结束后wg中的waitgoup被清零
                            // 然后跳出循环执行wg.Wait() 之后执行main函数然后结束
            fmt.Printf("the %d goroutine\n",i)
        }(i)
    }

    //等待知道计数为零
    wg.Wait()
    fmt.Println("main exit ....")
}


//执行结果如下

the 7 goroutine
the 3 goroutine
the 4 goroutine
the 5 goroutine
the 6 goroutine
the 0 goroutine
the 1 goroutine
the 2 goroutine
main exit ....


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容