Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a counter with atomic_fetch_add_explicit

Tags:

c

atomic

c11

#include <stdatomic.h>

void request_number(request_t *request)
{
    static atomic_int counter;

    request->id = atomic_fetch_add_explicit(&counter, 1, memory_order_relaxed);

    printf("Request assigned ID %u\n" request->id);
}

In the above C snippet, I believe it's ok to use memory_order_relaxed, because even without memory fences the compiler will not re-arrange the call to printf and fetch of request->id, before the store of the value for request->id.

Is this correct? I'm fairly certain it is but wanted to be absolutely sure in case there were other things that need to be taken into account with atomics.

like image 339
Arran Cudbard-Bell Avatar asked Feb 16 '26 06:02

Arran Cudbard-Bell


1 Answers

You are doing only one atomic operation and when you return from it you have your value. Everything else is done with the "normal" memory model as it would be for sequential code, like it always has been.

The ; at the end of the assignment is a sequence point. So your approach is perfectly fine. Indeed, the only thing that you need from your atomic operation here is that it is undivided, you don't need the sequencing guarantees of the "normal" atomic operations.

like image 73
Jens Gustedt Avatar answered Feb 18 '26 18:02

Jens Gustedt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!