Atomic<Point<float>> possible?


#1

Is it possible to wrap a Point<float> in an Atomic?

I tried and it breaks when setting the value as it calls the default constructor of Point<float> in order to call exchange internally.

But the default constructor of Point<float> is implicitly deleted according to the compiler:

template <typename Type>
inline Type Atomic<Type>::exchange (const Type newValue) noexcept
{
  #if JUCE_ATOMICS_MAC_LEGACY || JUCE_ATOMICS_GCC
    Type currentVal = value;
    while (! compareAndSetBool (newValue, currentVal)) { currentVal = value; }
    return currentVal;
  #elif JUCE_ATOMICS_WINDOWS
    return WindowsInterlockedHelpers<Type>::exchange (&value, newValue);
  #endif
}

In line 357 ("Type currentVal = value;") : No matching constructor for initialization of 'juce::Point<float>'

Is there a way to use this kind of construct?


#2

No, our Atomic classes will break if you try to use anything but a primitive type.

If you use std::atomic, it'll compile, but will probably implement it with a lock rather than actually being atomic!


#3

Ok, thanks for the explanation.

I will change my desing probably using a ringbuffer and take care, that my read pointer is always far enough away from the write pointer.


#4

To be more specific, you can use std::atomic<T> with any type T that is trivially copyable (no user-defined copy constructor, assignment etc.). Then, you can use the member function is_lock_free() to check if your atomic object is in fact lockfree.

I'd expect it to be lock-free for anything that's not larger than 8 bytes on a 64-bit Intel machine.


#5

Thanks for the hint. The is_lock_free() might become very handy.


#6

The only big caveat with std::atomic<T>::is_lock::free() is that you have to call it on an instance, you can't do it at compile time. The reason is that the C++ standard allows the "lock free" property of a std::atomic to vary from instance to instance of a given type T. It's a property of the object rather than the type.

In practice this won't really happen, at least not on Intel: data types that are small enough and trivially copyable will always be lockfree, other types won't.