tags:

views:

590

answers:

1

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;
}
+1  A: 

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.

claferri