Skip to content

gatomic: Add Compare and Exchange functions that returns the previous value

Marco Trevisan requested to merge 3v1n0/glib:atomic-exchange-pre-value into main

Atomic primitives allow to do conditional compare and exchange but also to get the value that was previously stored in the atomic variable.

Now, we provided an exchange function that allows to do an exchange if the atomic value matches an expected value but we had no way to know at the same time what was the value in the atomic at the moment of the exchange try, an this can be useful in case that the operation fails, for example if the current value is still acceptable for us, allowing to do a kind of "OR" check:

  gint old_value;
  gint valid_value = 222;
  while (!g_atomic_pointer_compare_and_exchange_value (&atomic,
                                                       valid_value, 555,
                                                       &old_value)
    {
      if (old_value == 555 || old_value == 222)
        valid_value = old_value;
    }

On naming, I'm not really sure if this _value suffix is fine... I initially wanted to call the functions g_atomic_<type>_compare_and_exchange_full, but I believe that a full version (if ever would be proposed), should also include the memory order flags, so I lost ideas in order to have a name that isn't super-long (given that the prefix is already quite a string!).

So, suggestions are very welcome.

Edited by Marco Trevisan

Merge request reports