如果有一個大迴圈,裡面每一個都開啟groutine,那麼瞬間就會開啟非常多的groutine,要解決這個問題就要用channel的阻塞特性來解決 看時間每次只是同時執行兩個 ...
如果有一個大迴圈,裡面每一個都開啟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
看時間每次只是同時執行兩個