superK
superK

Reputation: 3982

How can golang implement __sync_fetch_and_add like c(gcc buildin)?

In go's sync/atomic library, it seems there is no function like __sync_fetch_and_add in c(gcc buildin), it has

func AddInt32(addr *int32, delta int32) (new int32)
func AddInt64(addr *int64, delta int64) (new int64)
func AddUint32(addr *uint32, delta uint32) (new uint32)
func AddUint64(addr *uint64, delta uint64) (new uint64)
func AddUintptr(addr *uintptr, delta uintptr) (new uintptr)
func CompareAndSwapInt32(addr *int32, old, new int32) (swapped bool)
func CompareAndSwapInt64(addr *int64, old, new int64) (swapped bool)
...

etc.

It seems we only can implement it by CompareAndSwapxxx + while-loop, is it?

Upvotes: 0

Views: 407

Answers (1)

Thundercat
Thundercat

Reputation: 121099

Subtract delta from the AddXXX return value to get the original value.

Upvotes: 2

Related Questions