一、任意任务完成
import ( "fmt" "runtime" "testing" "time" ) func runTask(id int) string { time.Sleep(time.Millisecond * 10) return fmt.Sprintf("The result is from %d", id) } //任意任务完成 func FirstReponse() string { numOfRunner := 10 //buffer chan防止协程泄露 ch := make(chan string, numOfRunner) for i := 0; i < numOfRunner; i++ { go func(i int) { ret := runTask(i) ch <- ret }(i) } //任意任务完成 return <-ch }
二、全部任务完成
import ( "fmt" "runtime" "testing" "time" ) func runTask(id int) string { time.Sleep(time.Millisecond * 10) return fmt.Sprintf("The result is from %d", id) } //全部任务完成后返回 func AllReponse() string { numOfRunner := 10 //buffer chan防止协程泄露 ch := make(chan string, numOfRunner) for i := 0; i < numOfRunner; i++ { go func(i int) { ret := runTask(i) ch <- ret }(i) } finalRet := "" for n := 0; n < numOfRunner; n++ { finalRet += <-ch + "\n" } return finalRet }
三、测试
import ( "fmt" "runtime" "testing" "time" ) func runTask(id int) string { time.Sleep(time.Millisecond * 10) return fmt.Sprintf("The result is from %d", id) } //任意任务完成 func FirstReponse() string { numOfRunner := 10 //buffer chan防止协程泄露 ch := make(chan string, numOfRunner) for i := 0; i < numOfRunner; i++ { go func(i int) { ret := runTask(i) ch <- ret }(i) } //任意任务完成 return <-ch } //全部任务完成后返回 func AllReponse() string { numOfRunner := 10 //buffer chan防止协程泄露 ch := make(chan string, numOfRunner) for i := 0; i < numOfRunner; i++ { go func(i int) { ret := runTask(i) ch <- ret }(i) } finalRet := "" for n := 0; n < numOfRunner; n++ { finalRet += <-ch + "\n" } return finalRet } func TestFirstResponse(t *testing.T) { t.Log("Before:", runtime.NumGoroutine()) //t.Log(FirstReponse()) t.Log(AllReponse()) time.Sleep(time.Second * 1) t.Log("After:", runtime.NumGoroutine()) }
任意任务完成 === RUN TestFirstResponse first_response_test.go:48: Before: 2 first_response_test.go:49: The result is from 0 first_response_test.go:52: After: 2 --- PASS: TestFirstResponse (1.03s) PASS 全部任务完成 === RUN TestFirstResponse first_response_test.go:48: Before: 2 first_response_test.go:50: The result is from 4 The result is from 6 The result is from 9 The result is from 5 The result is from 1 The result is from 7 The result is from 8 The result is from 3 The result is from 0 The result is from 2 first_response_test.go:52: After: 2 --- PASS: TestFirstResponse (1.03s) PASS