Fetch_sub() in C++ example
Fetch_sub() in C++ provides operational support for the type to do atomic addition and subtraction on a stored address.
Fetch_sub() in C++
The operation work in the same ways as it is working as standard non-atomic pointer arithmetics. This executes the operation on atomic types but returns the pointer to the first element of an array. The fetch_sub is used to decrease the value. There are various parameters like-
- obj- Used in a pointer to the atomic object to modify.
- desr- Stores the value in the atomic object.
- order- Synchronises the memory ordering for this operation.
C++ code:
#include <iostream> #include<atomic> using namespace std; int main() { std::atomic<int> value; std::cout<<"Result returned from operation:"<<value.fetch_sub(5); std::cout<<"\nResult after operation:"<<value; std::cout<<"\nResult returned from operation:"<<value.fetch_add(3); std::cout<<"\nResult after operation:"<<value; std::cout<<"\nResult returned from operation:"<<value.fetch_and(4); std::cout<<"\nResult after operation:"<<value; std::cout<<"\nResult returned from operation:"<<value.fetch_or(2); std::cout<<"\nResult after operation:"<<value; std::cout<<"\nResult returned from operation:"<<value.fetch_xor(1); std::cout<<"\nResult after operation:"<<value; return 0; }
The various operations are used to perform various task.
Output:
Result returned from operation:0 Result after operation:-5 Result returned from operation:-5 Result after operation:-2 Result returned from operation:-2 Result after operation:4 Result returned from operation:4 Result after operation:6 Result returned from operation:6 Result after operation:7
First, the program is going to display the initial value in output i.e. 0. Then we can change its value using fetch add, fetch sub, fetch and, fetch or and fetch xor. We can use differ by using the different functions.
Leave a Reply