老师, 如果使用sync.WaitGroup的话, 发现每次输出的, After的gorountine的数量都是不同的, 这个应该怎么理解呢?
package ch22
import (
"fmt"
"runtime"
"sync"
"testing"
"time"
)
var wg sync.WaitGroup
func runTask(id int) string {
time.Sleep(time.Millisecond * 10)
return fmt.Sprintf("The result is from %d", id)
}
func FirstResponse() string {
numOfRunner := 10
ch := make(chan string, numOfRunner)
for i := 0; i < numOfRunner; i++ {
go func(i int) {
ch <- runTask(i)
}(i)
}
abc := <-ch
wg.Done()
return abc
}
func TestFirstResponse(t *testing.T) {
t.Log("Before:", runtime.NumGoroutine())
wg.Add(1)
t.Log(FirstResponse())
wg.Wait()
// time.Sleep(time.Second)
t.Log("After:", runtime.NumGoroutine())
}
展开
作者回复: 在检查协程数之前sleep一秒试试,让协程有时间完成和释放