[Go] Go routines with WaitGroup and async call
So, let's say we have a function to fetch crypto currencies price:
package main
import (
"fmt"
"sync"
"project/api"
)
func main() {
go getCurrencyData("BTC")
go getCurrencyData("BCH")
go getCurrencyData("ETH")
}
func getCurrencyData(currency string) {
rate, err := api.GetRate(currency)
if err == nil {
fmt.Printf("The rate for %v is %.2f \n", rate.Currency, rate.Price)
}
}
We know what will happen for this code, after main
function ends, all the program ends automaticlly, we might see nothing from the output.
WaitGroup
WaitGroup
can helps, let change code a little bit:
func main() {
currencies := []string {"BTC", "ETH", "BCH"}
var wg sync.WaitGroup
for _, currency := range currencies {
wg.Add(1)
go getCurrencyData(currency)
wg.Done()
}
wg.Wait()
}
Well, current code won't work, but it is important to understand what WaitGroup
doing for us, so basiclly it add 1 to a internal count of waitgroup by calling Add(1)
, and also subtract 1 by calling Done()
, Wait()
is used to wait the internal counter to be zero.
But why it doesn't work, it is because after go getCUrrencyData(currency)
, wg.Done()
get called immedicatly, we are not waiting go getCurrencyData(currency)
to finish at all
go getCurrencyData(cy) // do work in another thread
wg.Done() // continue in main thread
Using Async call
Now, let modify the code to make it work
func main() {
currencies := []string {"BTC", "ETH", "BCH"}
var wg sync.WaitGroup
for _, currency := range currencies {
wg.Add(1)
go func (cy string) {
getCurrencyData(cy)
wg.Done()
}(currency)
}
wg.Wait()
}
We wrap getCurrencyData
and wg.Done()
in a go func() {}()
.
Since getCurrencyData
and wg.Done()
are now working in sync, so wg.Done()
will actually work.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2023-02-06 [Typescript] Global Scope
2023-02-06 [Typescript] Indexing an Object with Branded Types
2019-02-06 [TypeScript] Type Definitions and Modules
2019-02-06 [Tools] Add a Dynamic Tweet Button to a Webpage
2019-02-06 [Algorithm] Find Nth smallest value from Array
2018-02-06 [Javascript] Delegate JavaScript (ES6) generator iteration control
2017-02-06 [React] Use React.cloneElement to Extend Functionality of Children Components