为了账号安全,请及时绑定邮箱和手机立即绑定

golang 并发问题

golang 并发问题

蛊毒传说 2019-04-08 11:18:03
import("fmt""runtime")/*结果:有时99有时100*/varcounter_numintconstMAXSIZE=100funcCount_num(chchanint){counter_num++ch
查看完整描述

2 回答

?
撒科打诨

TA贡献1934条经验 获得超2个赞

packagemain
import(
"fmt"
"runtime"
"sync/atomic"
)
/*
结果:
有时99
有时100
*/
varcounter_numuint32=0
constMAXSIZE=100
funcCount_num(chchanuint32){
atomic.AddUint32(&counter_num,1)
ch<-counter_num
}
funcmain(){
runtime.GOMAXPROCS(runtime.NumCPU())
varchs[MAXSIZE]chanuint32
fori:=0;ichs[i]=make(chanuint32)
goCount_num(chs[i])
}
fori,ch:=rangechs{
print("-----",i,"\n")
print(<-ch,"\n")
}
fmt.Println(counter_num)
}
                            
查看完整回答
反对 回复 2019-04-08
  • 2 回答
  • 0 关注
  • 418 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信