1 Star 0 Fork 0

c01dface/s-go-example

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
waitgroups.go 1.03 KB
一键复制 编辑 原始数据 按行查看 历史
c01dface 提交于 2024-12-05 19:00 . add waitgroups.go
package main
// To wait for multiple goroutines to finish, we can use a wait group
import (
"fmt"
"sync"
"time"
)
// This is the function we'll run in every goroutine
func worker(id int) {
fmt.Printf("Worker %d starting\n", id)
time.Sleep(time.Second)
fmt.Printf("Worker %d done\n", id)
}
func main() {
// This WaitGroup is used to wait for all the goroutines
// launched here to finish.
var wg sync.WaitGroup
// launch several goroutines and increment the WaitGroup counter
// for each
for i := 1; i <= 5; i++ {
wg.Add(1)
// Wrap the worker call in a closure that makes sure to tell
// the WaitGroup that this worker is done.
// This way the worker itself does not have to be aware of
// the concurrency primitives involved in its execution.
go func() {
// defer statement executed, and places
// wg.Done() on a list to be executed prior to the function returning
defer wg.Done()
worker(i)
}()
}
// Block until the WaitGroup counter goes back to 0
// all the workers notified they're done
wg.Wait()
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/vmalloc/s-go-example.git
git@gitee.com:vmalloc/s-go-example.git
vmalloc
s-go-example
s-go-example
master

搜索帮助