rowan.G
rowan.G

Reputation: 747

gcc builtin atomic compare and exchange

I want to use the gcc builtin function __atomic_compare_exchange() but I need it slightly different than it is specified as and it I am unsure it`s possible to achieve.

the function prototype:

__atomic_compare_exchange(type *ptr, type *expected, type *desired, bool weak, int success_memmodel, int failure_memmodel)

it atomically compares ptr to expected and writes desired into ptr if ptr == expected

what I want to achieve is very similiar but my expected is != NULL, basically I want to check if ptr != NULL and if that is true write desired into ptr.

can this be done?

here is the gcc concerning its usage:

https://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-Builtins.html

Upvotes: 2

Views: 2908

Answers (1)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215637

Sure, but you just have to call it in a loop. On each loop iteration, read the old value. If it's null, break out of the loop and return failure. If it's not null, use that old value as the "expected" for atomic compare-and-exchange. If it succeeds, exit the loop and return success. Otherwise repeat.

By the way, this general approach is how you construct arbitrary atomic operations on top of compare-and-exchange.

Upvotes: 3

Related Questions