#include#include int main() { std::atomic_int x = 10; int y = 5; int previous = x.fetch_add(y); std::cout << "Previous value of x: " << previous << std::endl; std::cout << "New value of x: " << x << std::endl; return 0; }
Previous value of x: 10 New value of x: 15
#include#include int main() { std::atomic pi = 3.14159; double delta = 0.00001; double previous = pi.fetch_add(delta); std::cout << "Previous value of pi: " << previous << std::endl; std::cout << "New value of pi: " << pi << std::endl; return 0; }
Previous value of pi: 3.14159 New value of pi: 3.1416000000000003In both examples, the `std::atomic_fetch_add` function is used to add a value to an atomic variable in a thread-safe and atomic manner. The `std::atomic` library in C++ provides a way to perform atomic operations on variables without using locks or other synchronization primitives.