在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
如果有一个大循环,里面每一个都开启groutine,那么瞬间就会开启非常多的groutine,要解决这个问题就要用channel的阻塞特性来解决 package main import "time" import "fmt" func main() { control := make(chan interface{}, 2) for i := 1; i <= 10; i++ { control <- i //这里应该放上面,如果放下面就会每次都执行三个了 go func(j int) { fmt.Printf("go func: %d, time: %d\n", j, time.Now().Unix()) time.Sleep(time.Second) <-control }(i) } //主groutine不要断 for { time.Sleep(time.Second) } } go func: 2, time: 1574427632 go func: 1, time: 1574427632 go func: 4, time: 1574427633 go func: 3, time: 1574427633 go func: 5, time: 1574427634 go func: 6, time: 1574427634 go func: 7, time: 1574427635 go func: 8, time: 1574427635 go func: 9, time: 1574427636 go func: 10, time: 1574427636 看时间每次只是同时执行两个 |
请发表评论