#include #include #include // For demonstration with multiple threads // A custom class that is trivially copyable struct MyData { int x1; double y1; // Default constructor MyData(int val_x = 0, double val_y = 0.0) : x1(val_x), y1(val_y) {} // No user-defined special member functions (copy/move constructors/assignments, destructor) // No virtual functions or virtual base classes }; // Overload operator== for MyData for use with compare_exchange_strong bool operator==(const MyData& lhs, const MyData& rhs) { return lhs.x1 == rhs.x1 && lhs.y1 == rhs.y1; } void worker_function(atomic& atomic_data) { MyData old_data; MyData new_data; // Perform a compare-and-swap loop to update the atomic MyData do { old_data = atomic_data.load(); // Atomically load the current value new_data = old_data; new_data.x1++; // Modify the copied data new_data.y1 += 0.1; } while (!atomic_data.compare_exchange_strong(old_data, new_data)); // Atomically attempt to update //If the compare_exchange operation failed then we try again. //else the old_data was replaced with new_data } int main() { atomic shared_data(MyData(10, 5.5)); // Initialize with a MyData object //load loads the current value cout << "Initial Data: x=" << shared_data.load().x << ", y=" << shared_data.load().y << endl; //worker_function needs a reference thread t1(worker_function, ref(shared_data)); thread t2(worker_function, ref(shared_data)); t1.join(); t2.join(); cout << "Final Data: x=" << shared_data.load().x1 << ", y=" << shared_data.load().y1 << endl; // You can also use store() and load() directly shared_data.store(MyData(20, 10.0)); cout << "Stored new Data: x=" << shared_data.load().x << ", y=" << shared_data.load().y << endl; return 0; }