Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap two pointers in multi-threaded c++ 17 program?

I have two pointers: pA and pB. They points to two big hash map objects. when the hash map pointed by pB is updated completely, I want to swap pB and pA.

In C++ 17, how to swap them fast and thread safe? Atomic? I am new to c++ 17.

like image 589
Dean Chen Avatar asked Aug 05 '26 15:08

Dean Chen


1 Answers

On x86-64 you can atomically exchange 2 pointers only if they are adjacent in memory and aligned to 16 bytes with cmpxchg16b instruction directly or by using libatomic_ops:

AO_INLINE int
AO_compare_double_and_swap_double_full(volatile AO_double_t *addr,
                                       AO_t old_val1, AO_t old_val2,
                                       AO_t new_val1, AO_t new_val2)
{
  char result;
  __asm__ __volatile__("lock; cmpxchg16b %0; setz %1"
                      : "=m"(*addr), "=a"(result)
                      : "m"(*addr), "d" (old_val2), "a" (old_val1),
                        "c" (new_val2), "b" (new_val1)
                      : "memory");
  return (int) result;
}

If cmpxchg16b is unavailable you need to use a mutex to make exchanging 2 pointers atomic.

like image 172
Maxim Egorushkin Avatar answered Aug 07 '26 06:08

Maxim Egorushkin



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!