[go学习笔记]二十九、go语言协程之所有任务都要完成!

166 阅读1分钟

示例代码请访问:github.com/wenjianzhan…

func runTask(id int) string {
	time.Sleep(10 * time.Millisecond)
	return fmt.Sprintf("The result is from %d\n", id)
}

func AllResponse() string {
	numOfRunner := 10
	ch := make(chan string, numOfRunner)
	for i := 0; i < numOfRunner; i++ {
		go func(i int) {
			ret := runTask(i)
			ch <- ret
		}(i)
	}
	finalRet := ""
	for j := 0; j < numOfRunner; j++ {
		finalRet += <-ch + ""
	}
	return finalRet
}

func TestFristResponse(t *testing.T) {
	t.Log("Before:", runtime.NumGoroutine())
	t.Log(AllResponse())
	time.Sleep(time.Second * 1)
	t.Log("After:", runtime.NumGoroutine())
}

输出

=== RUN   TestFristResponse
--- PASS: TestFristResponse (1.01s)
    untill_all_test.go:32: Before: 2
    untill_all_test.go:33: The result is from 0
        The result is from 1
        The result is from 9
        The result is from 6
        The result is from 7
        The result is from 8
        The result is from 4
        The result is from 2
        The result is from 5
        The result is from 3
        
    untill_all_test.go:35: After: 2
PASS

Process finished with exit code 0

全部任务都执行完成

示例代码请访问:github.com/wenjianzhan…