func main() {
result, err := test()
if err != nil {
fmt.Println("err", err)
}
fmt.Println("test", result)
}
func test() ([]T, error) {
var slice []T
var wg sync.WaitGroup
queue := make(chan T)
// Poll the queue for data and append it to the slice.
// Since this happens synchronously and in the same
// goroutine/thread, this can be considered safe.
// Create our data and send it into the queue.
for i := 0; i < 100; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
// Do stuff.
runtime.Gosched()
queue <- T(i)
}(i)
}
go func() {
wg.Wait()
//when all gorotuines are asleep,close channel
close(queue)
}()
//if channel is not closed,this channel will be blocked
for t := range queue {
slice = append(slice, t)
}
return slice, nil
}