package concurrent_test import ( "fmt" "math/rand" "sync" "testing" "time" ) func init() { rand.Seed(time.Now().UnixNano()) } // 使用channel控制并发数 var lst = []string{ "whw1", "whw2", "whw3", "whw4", "whw5", "whw6", "whw7", "whw8", "whw9", "whw10", "whw11", "whw12", "whw13", "whw14", "whw15", "whw16", "whw17", "whw18", "whw19", } func TestChanControlGos(t *testing.T) { var wg sync.WaitGroup limitChan := make(chan struct{}, 3) // 最多同时有3个协裎同时工作 for _, item := range lst { wg.Add(1) limitChan <- struct{}{} // 注意: 如果要用lst中的元素,一定要定义在func下并当作参数传入! go func(s string) { defer wg.Done() consumeStr(s, limitChan) }(item) } wg.Wait() fmt.Println("主协裎结束......") } func consumeStr(name string, limitCh chan struct{}) { defer func() { <-limitCh }() time.Sleep(time.Duration(rand.Intn(2)) * time.Second) // 模拟延迟 fmt.Println("name: ", name) }
~~~
标签:wg,控制,string,rand,fmt,并发,func,time,channel From: https://www.cnblogs.com/paulwhw/p/16955785.html