Home > Software engineering >  In C using Clang atomics, how should I perform an atomic pre-increment?
In C using Clang atomics, how should I perform an atomic pre-increment?

Time:06-11

Expanding from this question (How to do an atomic increment and fetch in C?)

In C, using Clang compiler, how can I do the atomic equivalent of

const int v = x

As I understand it, v = atomic_fetch_add(&x, 1) will return the original value (ie v = x ), which is a post-increment.

How do I return the updated value of x instead?

Note: this question is about C, and any replies with "use std::atomic<>" will be downvoted accordingly.

CodePudding user response:

You can use

v = atomic_fetch_add(&x, 1)   1;

CodePudding user response:

You can use the clang/gcc intrinsic function __atomic_add_fetch(), which first adds to a number then returns the new value (There's also __atomic_fetch_add() which acts like the C11 atomic_fetch_add()):

int x = 1;
const int v = __atomic_add_fetch(&x, 1, __ATOMIC_SEQ_CST); // v is 2
  • Related