一起学go开发:goroutine并发
在语言里有一种机制保证并发安全,即:goroutine,又叫:go程,先来看一段代码:
1 2 3 4 5 6 7 | func Starter() { fmt.Println( "This is the starter on call" ) } func Follow() { fmt.Println( "This is the follower on call" ) } |
1 2 | hello.Starter() hello.Follow() |
在常规情况下,代码是按照函数的调用顺序执行的,但如果我们使用go程以后,又会怎样呢?
1 2 | go hello.Starter() hello.Follow() |
当使用go程以后,多次执行代码我们会发现函数的执行不再按照预期的顺序执行了,这就是所谓的并发。
现在思考一下:如果要给Starter使用go程,同时还想保持先执行Starter函数,再执行Follow函数,该怎么实现呢?
很庆幸的是,go的sync.WaitGroup机制可以帮我们实现这个需求,实现代码如下:
1 2 3 4 5 6 7 8 | func Starter1(wg *sync.WaitGroup) { fmt.Println( "This is the starter1 on call" ) defer wg.Done() } func Follow1() { fmt.Println( "This is the follower1 on call" ) } |
1 2 3 4 5 | var wg sync.WaitGroup wg.Add(1) go hello.Starter1(&wg) // 使用sync.WaitGroup确保goroutine执行完成 wg.Wait() hello.Follow1() |
sync.WaitGroup
provides a goroutine synchronization mechanism in Golang
, and is used for waiting for a collection of goroutines to finish.
sync.WaitGroup机制用于保证一组goroutine执行完成。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?