Atomic exchange in C

I think I missed something obvious here. I have a code like this:

int *a = <some_address>;
int *b = <another_address>;
[...]
int *tmp = a;
a = b; b = tmp;

I want to do it atomically. I looked at __c11_atomic_exchange, and on OSX, the OSAtomic methods, but nothing seems to perform direct atomic exchanges. They can write a value in 1 of 2 variables atomically, but never both.

Any ideas?

+4
source share
1 answer

It depends a little on your architecture, which is efficient and effective. In any case, you will need that the two pointers you want to swap are adjacent in memory, the simplest that you have, such as some, for example

typedef struct pair { void *a[2]; } pair;

, C11, _Atomic(pair) , pair: , , , , :

inline
void pair_swap(_Atomic(pair) *myPair) {
  pair actual = { 0 };
  pair future = { 0 };

  while (!atomic_compare_exchange_weak(myPair, &actual, future)) {
      future.a[0] = actual.a[1];
      future.a[1] = actual.a[0];
  }
}

. 64- 128- , 128 .

. P99 , "" 128- , ; (64- Intel Linux) lock cmpxchg16b.

+5

All Articles