Page 1 of 1

Atomically check and set only if not already set

Posted: Sat Aug 27, 2011 9:26 am
by limp
Hi all,

I have found a couple of ways regarding how to atomically check a register or mem. location and change its value to something else (on x86) but I haven't found anything regarding the following:

Test (atomically) a memory location (which is used as flag for instance) and set it only if it's not already set, otherwise do nothing.

In pseudocode, this should look similar to that:

Code: Select all

/* all this should be done atomically */
check mem location 0x1000
if *(uint32_t 0x1000 *) == 0x1
	do nothing
else
	/* set to 0x1 */
	*(uint32_t 0x1000 *) = 0x1
Any help on that will be really appreciated.

Re: Atomically check and set only if not already set

Posted: Sat Aug 27, 2011 10:12 am
by XanClic
(lock) cmpxchg is your friend; regarding gcc, there are also atomic builtins such as __sync_bool_compare_and_swap (see http://gcc.gnu.org/onlinedocs/gcc/Atomic-Builtins.html).

Re: Atomically check and set only if not already set

Posted: Sat Aug 27, 2011 2:11 pm
by limp
Hi,
XanClic wrote:(lock) cmpxchg is your friend; regarding gcc, there are also atomic builtins such as __sync_bool_compare_and_swap (see http://gcc.gnu.org/onlinedocs/gcc/Atomic-Builtins.html).
I haven't tried it yet but it seems that that's what I was looking for, thanks!

Re: Atomically check and set only if not already set

Posted: Sat Aug 27, 2011 4:17 pm
by Combuster
Don't forget the LOCK prefix if you do. And while compare-and-swap is a good generic implementation, a test-and-set will work as well (and LOCK BTR/BTS/BTC is supported even up to the 386s)