10

I am aware of GCC's builtin atomic operations: http://gcc.gnu.org/onlinedocs/gcc-4.3.2/gcc/Atomic-Builtins.html

But this list doesn't include very simple operations like load and store. I could implement these on limited architectures with inline assembly (in fact for many like x86 they will be basically just regular mov's), but is there no better way in the general case than something like this:

// returns the value at ptr
void *atomic_load_ptr(void **ptr)
{
    return __sync_fetch_and_add(ptr, 0);
}

// returns old value int ptr after setting it to newval
void *atomic_store_ptr(void **ptr, void *newval)
{
    void *oldval = atomic_load_ptr(ptr)
    void *oldval2;
    do {
        oldval2 = oldval;
    } while ((oldval = __sync_val_compare_and_swap(ptr, oldval, newval)) != oldval2);
    return oldval;
}
3
  • Stop me if I'm wrong, but your "store" function isn't really a store as it returns the old value (so it is very close to CAS). Commented May 4, 2009 at 8:56
  • Its really an "exchange" - storing a new value and returning the previous value if you want it. Commented May 4, 2009 at 13:29
  • I have found that this load implementation has a problem: it can't be used on read-only memory. Commented Aug 27, 2014 at 12:58

1 Answer 1

2

You could implement low level mutex with test_and_set. The load function is a good one imo, but you store function should use test_and_set instead of having

while ((oldval = __sync_val_compare_and_swap(ptr, oldval, newval)) != oldval2);

to prevent errors.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.