Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to implement a generic atomic load or store in GCC?

Tags:

c

gcc

atomic

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;
}
like image 921
Greg Rogers Avatar asked May 02 '09 01:05

Greg Rogers


1 Answers

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.

like image 101
claf Avatar answered Nov 17 '22 10:11

claf