
因为go语言层面支持并发,所以面试中经常会问到并发的问题,比如说控制go并发数量的方式有哪些?下面是我个人整理的两个例子:
func waitGroup() {
count := 10
wg := sync.WaitGroup{}
for i := 0; i <p>上面主要用到的是go中sync包下的waitGroup,这也是在工作中比较常见的实现方式,关键点就是把握好Add方法的位置,Wait方法则是等待所有的协程执行完毕</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/gongju/2525" title="Go语言(Golang)1.26.0"><img
src="https://img.php.cn/upload/manual/001/589/237/6a6adeed24a4a355.png" alt="Go语言(Golang)1.26.0" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/gongju/2525" title="Go语言(Golang)1.26.0" class="overflowclass">Go语言(Golang)1.26.0</a>
<p class="overflowclass">Go语言(Golang)1.26.0版本官方下载,版本号 1.26.0,适合旧项目维护、兼容性测试和指定版本开发环境搭建。</p>
</div>
<a rel="nofollow" href="/xiazai/gongju/2525" title="Go语言(Golang)1.26.0" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><pre class="brush:php;toolbar:false">func channel() {
count := 10 // 最大支持并发
sum := 100 // 任务总数
c := make(chan struct{}, count) // 控制任务并发的chan
sc := make(chan struct{}, sum) // 控制任务总数的chan
defer close(c)
defer close(sc)
for i:=0; i<sum>0;i-- {
<p>上面的例子用到的是go中的channel,利用channel阻塞的特性和带缓冲的channel来实现控制并发数量,其中sc这个channel是可以去掉的,例子里用只是为了防止主程序退出之后,没有全部输出,正常工作中,程序一般都是阻塞式的,所以可以去掉。</p>
<p>更多相关知识请关注go语言教程栏目</p></sum>golang免费学习笔记(深入):立即使用
在学习笔记中,你将探索golang的核心概念和高级技巧!










