您的位置 首页 golang

Golang面试遇到的问题–控制goroutine的并发数量

问题

使用goroutine的时候,如何控制并发的数量。

下面是一个简单的实现思路,用带 缓存 的channel

code

import (
	"fmt"
	"sync"
	"time"
)
var wg sync.WaitGroup
func main() {
	userCount := 10
	 ch  := make(chan bool, 2)
	for i := 0; i < userCount; i++ {
		go Read(ch, i)
	}
	wg.Wait()
}
func Read(ch chan bool, i int) {
	defer wg.Done()
	wg.Add(1)
	ch <- true
	//do some work here
	fmt.Println("i:", i, ":", time.Now(). Unix ())
	time.Sleep(time.Second)
	<-ch
}
 

文章来源:智云一二三科技

文章标题:Golang面试遇到的问题–控制goroutine的并发数量

文章地址:https://www.zhihuclub.com/101833.shtml

关于作者: 智云科技

热门文章

网站地图