golang 实现cas
相比sync.WaitGroup里面的互斥锁,cas可以实现无锁等待一组任务执行完成后释放,示例代码如下
func TestCAS(t *testing.T) {
var count int32 = 10000
for i := 0; i < int(count); {
go func() {
defer func() { atomic.AddInt32(&count, -1) }()
//do something
//...
}()
}
for atomic.LoadInt32(&count) > 0 {
}
t.Log("task exec finished")
}