🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
可以使用sync.WaitGroup实现,这里使用CSP模式介绍另一种方式 ~~~ func DoTask(num int) string { fmt.Println("run task", num) return fmt.Sprintf("run task finished %v", num) } func TestOneTaskRunReturnAll(t *testing.T) { taskNum := 10 fmt.Println("before goroutine num:", runtime.NumGoroutine()) result := make(chan string, taskNum) for i := 1; i <= taskNum; i++ { go func(transId int) { taskResult := DoTask(transId) result <- taskResult }(i) } str := "" for i := 1; i <= taskNum; i++ { str += <-result + "\n" } time.Sleep(2 * time.Second) fmt.Println("main goroutine result:", str) fmt.Println("after goroutine num:", runtime.NumGoroutine()) } ~~~