golang 并行执行多任务-有返回值
func main() {
now := time.Now()
var wg sync.WaitGroup
wg.Add(3)
resMap := make(map[string]string)
go func() {
defer wg.Done()
resMap["key1"] = OtherMethod(1)
}()
go func() {
defer wg.Done()
resMap["key2"] = OtherMethod(5)
}()
go func() {
defer wg.Done()
resMap["key5"] = OtherMethod(10)
}()
wg.Wait()
marshal, _ := json.Marshal(resMap)
log.Println("最终结果:", string(marshal))
log.Println("耗时:", time.Since(now))
}
// @Description: 模拟执行外部任务
// @Author:luog
// @date: 2023-02-23 11:11:09
// @param sleepTime
// @return string
func OtherMethod(sleepTime int) string {
log.Println("开始执行任务_", sleepTime)
for i := 0; i < sleepTime; i++ {
time.Sleep(time.Second)
}
log.Println("任务完成_", sleepTime)
return "结果_" + strconv.Itoa(sleepTime)
}