Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::atomic_ref<T>::atomic_ref

      From cppreference.com
      <cpp‎ |atomic‎ |atomic ref
       
       
      Concurrency support library
      Threads
      (C++11)
      (C++20)
      this_thread namespace
      (C++11)
      (C++11)
      (C++11)
      Cooperative cancellation
      Mutual exclusion
      Generic lock management
      (C++11)
      (C++11)
      (C++11)
      (C++11)
      Condition variables
      (C++11)
      Semaphores
      Latches and Barriers
      (C++20)
      (C++20)
      Futures
      (C++11)
      (C++11)
      (C++11)
      Safe reclamation
      Hazard pointers
      Atomic types
      (C++11)
      (C++20)
      Initialization of atomic types
      (C++11)(deprecated in C++20)
      (C++11)(deprecated in C++20)
      Memory ordering
      (C++11)(deprecated in C++26)
      Free functions for atomic operations
      Free functions for atomic flags
       
      std::atomic_ref
      Member functions
      atomic_ref::atomic_ref
      Operations for arithmetic types
      (exceptbool and pointer-to-object)
      Operations for integral types
      (exceptbool and pointer-to-object)
      Operations for integral types
      (exceptbool)
      Constants
       
      explicit atomic_ref( T& obj);
      (1)(constexpr since C++26)
      atomic_ref(const atomic_ref& ref)noexcept;
      (2)(constexpr since C++26)

      Constructs a newatomic_ref object.

      1) Constructs anatomic_ref object referencing the objectobj.
      Ifobj is not aligned torequired_alignment, the behavior is undefined.
      2) Constructs anatomic_ref object referencing the object referenced byref.

      [edit]Parameters

      obj - object to reference
      ref - anotheratomic_ref object to copy from

      [edit]Example

      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 <iostream>#include <numeric>#include <thread>#include <vector> 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=[](constauto 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);}

      Possible output:

      sum = 40000000sum = 39994973
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/atomic/atomic_ref/atomic_ref&oldid=179445"

      [8]ページ先頭

      ©2009-2026 Movatter.jp