Atomically check and set only if not already set

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
limp
Member
Member
Posts: 90
Joined: Fri Jun 12, 2009 7:18 am

Atomically check and set only if not already set

Post 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.
User avatar
XanClic
Member
Member
Posts: 138
Joined: Wed Feb 13, 2008 9:38 am

Re: Atomically check and set only if not already set

Post 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).
limp
Member
Member
Posts: 90
Joined: Fri Jun 12, 2009 7:18 am

Re: Atomically check and set only if not already set

Post 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!
User avatar
Combuster
Member
Member
Posts: 9301
Joined: Wed Oct 18, 2006 3:45 am
Libera.chat IRC: [com]buster
Location: On the balcony, where I can actually keep 1½m distance
Contact:

Re: Atomically check and set only if not already set

Post 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)
"Certainly avoid yourself. He is a newbie and might not realize it. You'll hate his code deeply a few years down the road." - Sortie
[ My OS ] [ VDisk/SFS ]
Post Reply