GSP
Quick Navigator

Search Site

Unix VPS
A - Starter
B - Basic
C - Preferred
D - Commercial
MPS - Dedicated
Previous VPSs
* Sign Up! *

Support
Contact Us
Online Help
Handbooks
Domain Status
Man Pages

FAQ
Virtual Servers
Pricing
Billing
Technical

Network
Facilities
Connectivity
Topology Map

Miscellaneous
Server Agreement
Year 2038
Credits
 

USA Flag

 

 

Man Pages
std::atomic_ref::atomic_ref(3) C++ Standard Libary std::atomic_ref::atomic_ref(3)

std::atomic_ref::atomic_ref - std::atomic_ref::atomic_ref


explicit atomic_ref( T& obj ); (1) (since C++20)
atomic_ref( const atomic_ref& ref ) noexcept; (2) (since C++20)


Constructs a new atomic_ref object.


1) Constructs an atomic_ref object referencing the object obj. The behavior is
undefined if obj is not aligned to required_alignment.
2) Constructs an atomic_ref object referencing the object referenced by ref.


obj - object to reference
ref - another atomic_ref object to copy from


The program increments the values in a container using several threads. Then the
final sum is printed. Non-atomic access may "loss" the results of some operations
due to data-races.

// Run this code


#include <atomic>
#include <thread>
#include <vector>
#include <numeric>
#include <iostream>


int main()
{
using Data = std::vector<char>;


auto inc_atomically = [](Data& data) {
for (Data::value_type& x : data) {
auto xx = std::atomic_ref<Data::value_type>(x);
++xx; // atomic read-modify-write
}
};


auto inc_directly = [](Data& data) {
for (Data::value_type& x : data)
++x;
};


auto test_run = [](const auto Fun) {
Data data(10'000'000);
{
std::jthread j1 {Fun, std::ref(data)};
std::jthread j2 {Fun, std::ref(data)};
std::jthread j3 {Fun, std::ref(data)};
std::jthread j4 {Fun, std::ref(data)};
}
std::cout << "sum = " << std::accumulate(cbegin(data), cend(data), 0) << '\n';
};


test_run(inc_atomically);
test_run(inc_directly);
}


sum = 40000000
sum = 39994973

2022.07.31 http://cppreference.com

Search for    or go to Top of page |  Section 3 |  Main Index

Powered by GSP Visit the GSP FreeBSD Man Page Interface.
Output converted with ManDoc.