I came across an atomic "fetch and store" instruction in the description of an MCS lock.
From what I gather, this atomically writes a value to a memory location and returns the original value of that memory location, is that correct?
And is gcc's atomic builtin,
__sync_lock_test_and_set
the same as an atomic fetch and store?
Per the GCC info page, this is indeed atomic, but it's not the basic atomic fetch and store.
(this is clipped from the 4.4 manual, so different section number)
They're apparently taken from the Intel Itanium reference manual, but GCC implements them on any CPU they can be (and warns if you use one on a CPU that doesn't, then uses a non-atomic version). The function you noted is actually an extended memory barrier (or critical area): the barrier is established by
__sync_lock_test_and_set
, and released by__sync_lock_release
.If you're looking for a basic atomic fetch-and-set, it's probably
__sync_val_compare_and_swap
although in most cases you'll want to use one of the more specific versions.