i want to implement add below in pure atomic operation
var num int
func add(max int) int {
if num < max {
num++
}
return num
}
i have try one edition
func add(max int64) int64 {
for {
old := atomic.LoadInt64(&x)
if old + 1 < max {
if atomic.CompareAndSwapInt64(&x, old, old+1) {
return old+1
}
} else {
return old
}
}
}
however, i guess there might be a better solution with less fail chance and avoid dead loop