chan
package main
import (
"fmt"
"sync"
"time"
)
var wg = sync.WaitGroup{}
func dispatch(c chan int, i int) {
c <- i
}
func receive(c chan int) {
L:
for {
select {
case data := <-c:
fmt.Println(data)
wg.Done()
case <-time.After(time.Second * 5):
fmt.Println("done")
break L
}
}
}
func main() {
chan1 := make(chan int, 0)
for i := 0; i < 100; i++ {
wg.Add(1)
go dispatch(chan1, i)
}
receive(chan1)
wg.Wait()
}
可以参考:
- 1 . https://gobyexample.com/waitgroups
- 2 . https://www.cnblogs.com/wangxusummer/p/4229418.html
- 3 . https://stanzhai.site/blog/post/stanzhai/go%E4%B8%BAchannel%E8%AE%BE%E7%BD%AE%E8%B6%85%E6%97%B6%E7%9A%84%E6%AD%A3%E7%A1%AE%E5%A7%BF%E5%8A%BF
注意 退出for select 需在receiver的function里面打个tag