Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Atomic decrement-and-test in C

I'm implementing a reference-counting system in C that needs to work with multiple threads. As a result, I need a way to decrement an integral reference count and test if the result is zero with one atomic operation. I can use C11 and stdatomic.h, but there doesn't seem to be a decrement-and-test operation.

What's the best (i.e. most portable) way of going about this? Can I use the stdatomic.h functions to achieve this?


This is the core of the reference counting (pseudocode):

retain(object) {
    ++object.ref_count;  // pretty easy to make this atomic
} 

release(object) {
    if (--object.ref_count == 0)  // need this to be atomic also
        free(object)
}
like image 749
user6149363 Avatar asked Jun 18 '16 17:06

user6149363


1 Answers

You seem to have a misconsception of C11's atomics. Atomic qualifies a type, not a single operation.

If you declare your variable with _Atomic all operations on it are atomic. So if you are satisfied with the default "sequential consistency" of the atomic operations (which you should), an additional _Atomic qualification is all you need. And the prefix -- operator should work fine for what you need.

If you want do deal with different types of consistency you could use atomic_fetch_sub, e.g. Only that then you obtain the value before the modification and not the one after. So instead of comparing to 0 you should then compare it to 1.

like image 189
Jens Gustedt Avatar answered Nov 18 '22 09:11

Jens Gustedt