Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/atomic/atomic fetch add"

From cppreference.com
< cpp‎ | atomic
m (Possible implementation)
m (Return value: #)
 
(7 intermediate revisions by 5 users not shown)
Line 1: Line 1:
 
{{cpp/title|atomic_fetch_add|atomic_fetch_add_explicit}}
 
{{cpp/title|atomic_fetch_add|atomic_fetch_add_explicit}}
{{cpp/atomic/navbar}}
+
{{cpp/thread/navbar}}
 
{{dcl begin}}
 
{{dcl begin}}
{{dcl header | atomic }}
+
{{dcl header|atomic}}
{{dcl rev begin | num=1 }}
+
{{dcl|num=1|since=c++11|
{{dcl |  
+
 
template< class T >
 
template< class T >
 
T atomic_fetch_add( std::atomic<T>* obj,
 
T atomic_fetch_add( std::atomic<T>* obj,
 
                     typename std::atomic<T>::difference_type arg ) noexcept;
 
                     typename std::atomic<T>::difference_type arg ) noexcept;
 
}}
 
}}
{{dcl |
+
{{dcl|num=2|since=c++11|
 
template< class T >
 
template< class T >
 
T atomic_fetch_add( volatile std::atomic<T>* obj,
 
T atomic_fetch_add( volatile std::atomic<T>* obj,
 
                     typename std::atomic<T>::difference_type arg ) noexcept;
 
                     typename std::atomic<T>::difference_type arg ) noexcept;
 
}}
 
}}
{{dcl rev end}}
+
{{dcl|num=3|since=c++11|
{{dcl rev begin | num=2 }}
+
{{dcl |  
+
 
template< class T >
 
template< class T >
T atomic_fetch_add_explicit( std::atomic<T>* obj,  
+
T atomic_fetch_add_explicit( std::atomic<T>* obj,
                             typename std::atomic<T>::difference_type arg,  
+
                             typename std::atomic<T>::difference_type arg,
 
                             std::memory_order order ) noexcept;
 
                             std::memory_order order ) noexcept;
 
}}
 
}}
{{dcl |  
+
{{dcl|num=4|since=c++11|
 
template< class T >
 
template< class T >
 
T atomic_fetch_add_explicit( volatile std::atomic<T>* obj,
 
T atomic_fetch_add_explicit( volatile std::atomic<T>* obj,
                             typename std::atomic<T>::difference_type arg,  
+
                             typename std::atomic<T>::difference_type arg,
 
                             std::memory_order order ) noexcept;
 
                             std::memory_order order ) noexcept;
 
}}
 
}}
{{dcl rev end}}
 
 
{{dcl end}}
 
{{dcl end}}
  
Performs atomic addition. Atomically adds {{tt|arg}} to the value pointed to by {{tt|obj}} and returns the value {{tt|obj}} held previously. The operation is performed as if the following was executed:
+
Performs atomic addition. Atomically adds {{c|arg}} to the value pointed to by {{c|obj}} and returns the value {{c|obj}} held previously. The operation is performed as if the following was executed:
 +
@1,2@ {{c|obj->fetch_add(arg)}}
 +
@3,4@ {{c|obj->fetch_add(arg, order)}}
  
:@1@ {{c|obj->fetch_add(arg)}}
+
If {{tt|std::atomic<T>}} has no {{tt|fetch_add}} member (this member is only provided for {{rlp|atomic#Specializations for integral types|integral}}{{rev inl|since=c++20|, {{rlp|atomic#Specializations for floating-point types|floating-point}}}} and {{rlp|atomic#Partial specializations|pointer}} types except {{c/core|bool}}), the program is ill-formed.
 
+
:@2@ {{c|obj->fetch_add(arg, order)}}
+
  
 
===Parameters===
 
===Parameters===
 
{{par begin}}
 
{{par begin}}
{{par | obj | pointer to the atomic object to modify}}
+
{{par|obj|pointer to the atomic object to modify}}
{{par | arg | the value to add to the value stored in the atomic object}}
+
{{par|arg|the value to add to the value stored in the atomic object}}
{{par | order | the memory synchronization ordering for this operation: all values are permitted.}}
+
{{par|order|the memory synchronization ordering}}
{{par end}}  
+
{{par end}}
  
 
===Return value===
 
===Return value===
The value immediately preceding the effects of this function in the [[cpp/atomic/memory_order#Modification_order|modification order]] of {{tt|*obj}}.
+
The value immediately preceding the effects of this function in the {{lsd|cpp/atomic/memory order#Modification order}} of {{c|*obj}}.
 
+
===Possible implementation===
+
{{eq fun
+
| 1=
+
template< class T >
+
T atomic_fetch_add( std::atomic<T>* obj, typename std::atomic<T>::difference_type arg )
+
{
+
    return obj->fetch_add(arg);
+
}
+
}}
+
  
 
===Example===
 
===Example===
 
{{example
 
{{example
| Single-writer/multiple-reader lock can be made with fetch_add. Note that this simplistic implementation is not lockout-free
+
|Single-writer/multiple-reader lock can be made with {{tt|std::atomic_fetch_add}}. Note that this simplistic implementation is not lockout-free.
| code=
+
|code=
 +
#include <atomic>
 +
#include <chrono>
 +
#include <iostream>
 
#include <string>
 
#include <string>
 
#include <thread>
 
#include <thread>
 
#include <vector>
 
#include <vector>
#include <iostream>
+
 
#include <atomic>
+
using namespace std::chrono_literals;
#include <chrono>
+
 
+
 
// meaning of cnt:
 
// meaning of cnt:
// 5: there are no active readers or writers.
+
// 5: readers and writer are in race. There are no active readers or writers.
// 1...4: there are 4...1 readers active, The writer is blocked
+
// 4...0: there are 1...5 active readers, The writer is blocked.
// 0: temporary value between fetch_sub and fetch_add in reader lock
+
// -1: writer won the race and readers are blocked.
// -1: there is a writer active. The readers are blocked.
+
 
 
const int N = 5; // four concurrent readers are allowed
 
const int N = 5; // four concurrent readers are allowed
 
std::atomic<int> cnt(N);
 
std::atomic<int> cnt(N);
Line 80: Line 68:
 
void reader(int id)
 
void reader(int id)
 
{
 
{
     for(;;)
+
     for (;;)
 
     {
 
     {
 
         // lock
 
         // lock
         while(std::atomic_fetch_sub(&cnt, 1) <= 0)
+
         while (std::atomic_fetch_sub(&cnt, 1) <= 0)
 
             std::atomic_fetch_add(&cnt, 1);
 
             std::atomic_fetch_add(&cnt, 1);
 +
       
 
         // read
 
         // read
         if(!data.empty())
+
         if (!data.empty())
             std::cout << ( "reader " + std::to_string(id)
+
             std::cout << ("reader " + std::to_string(id) +
                           + " sees " + std::to_string(*data.rbegin()) + '\n');
+
                           " sees " + std::to_string(*data.rbegin()) + '\n');
         if(data.size() == 25)
+
         if (data.size() == 25)
 
             break;
 
             break;
 +
       
 
         // unlock
 
         // unlock
 
         std::atomic_fetch_add(&cnt, 1);
 
         std::atomic_fetch_add(&cnt, 1);
 +
       
 
         // pause
 
         // pause
         std::this_thread::sleep_for(std::chrono::milliseconds(1));
+
         std::this_thread::sleep_for(1ms);
 
     }
 
     }
 
}
 
}
Line 100: Line 91:
 
void writer()
 
void writer()
 
{
 
{
     for(int n = 0; n < 25; ++n)
+
     for (int n = 0; n < 25; ++n)
 
     {
 
     {
 
         // lock
 
         // lock
         while(std::atomic_fetch_sub(&cnt, N+1) != N)
+
         while (std::atomic_fetch_sub(&cnt, N + 1) != N)
             std::atomic_fetch_add(&cnt, N+1);
+
             std::atomic_fetch_add(&cnt, N + 1);
 +
       
 
         // write
 
         // write
 
         data.push_back(n);
 
         data.push_back(n);
 
         std::cout << "writer pushed back " << n << '\n';
 
         std::cout << "writer pushed back " << n << '\n';
 +
       
 
         // unlock
 
         // unlock
         std::atomic_fetch_add(&cnt, N+1);
+
         std::atomic_fetch_add(&cnt, N + 1);
 +
       
 
         // pause
 
         // pause
         std::this_thread::sleep_for(std::chrono::milliseconds(1));
+
         std::this_thread::sleep_for(1ms);
 
     }
 
     }
 
}
 
}
Line 118: Line 112:
 
{
 
{
 
     std::vector<std::thread> v;
 
     std::vector<std::thread> v;
     for (int n = 0; n < N; ++n) {
+
     for (int n = 0; n < N; ++n)
 
         v.emplace_back(reader, n);
 
         v.emplace_back(reader, n);
    }
 
 
     v.emplace_back(writer);
 
     v.emplace_back(writer);
     for (auto& t : v) {
+
   
 +
     for (auto& t : v)
 
         t.join();
 
         t.join();
    }
 
 
}
 
}
| output=
+
|output=
 
writer pushed back 0
 
writer pushed back 0
 
reader 2 sees 0
 
reader 2 sees 0
Line 139: Line 132:
 
===Defect reports===
 
===Defect reports===
 
{{dr list begin}}
 
{{dr list begin}}
{{dr list item|std=C++11|paper=P0558R1|before=exact type match required because {{tt|T}} is deduced from multiple arguments|after={{tt|T}} is deduced from the {{tt|atomic}} argument only}}
+
{{dr list item|std=C++11|paper=P0558R1|before=exact type match was required because<br>{{tt|T}} was deduced from multiple arguments|after={{tt|T}} is only deduced<br>from {{c|obj}}}}
 
{{dr list end}}
 
{{dr list end}}
  
 
===See also===
 
===See also===
 
{{dsc begin}}
 
{{dsc begin}}
{{dsc inc | cpp/atomic/atomic/dsc fetch_add}}
+
{{dsc inc|cpp/atomic/atomic/dsc fetch_add}}
{{dsc inc | cpp/atomic/dsc atomic_fetch_sub}}
+
{{dsc inc|cpp/atomic/dsc atomic_fetch_sub}}
{{dsc see c | c/atomic/atomic_fetch_add | atomic_fetch_add | atomic_fetch_add_explicit}}
+
{{dsc see c|c/atomic/atomic_fetch_add|atomic_fetch_add|atomic_fetch_add_explicit}}
 
{{dsc end}}
 
{{dsc end}}
  
 
{{langlinks|de|es|fr|it|ja|pt|ru|zh}}
 
{{langlinks|de|es|fr|it|ja|pt|ru|zh}}

Latest revision as of 08:10, 25 October 2023

 
 
Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
(C++11)
Cooperative cancellation
Mutual exclusion
(C++11)
Generic lock management
(C++11)
(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)
(C++11)
Safe Reclamation
(C++26)
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
Free functions for atomic operations
atomic_fetch_addatomic_fetch_add_explicit
(C++11)(C++11)
Free functions for atomic flags
 
Defined in header <atomic>
template< class T >

T atomic_fetch_add( std::atomic<T>* obj,

                    typename std::atomic<T>::difference_type arg ) noexcept;
(1) (since C++11)
template< class T >

T atomic_fetch_add( volatile std::atomic<T>* obj,

                    typename std::atomic<T>::difference_type arg ) noexcept;
(2) (since C++11)
template< class T >

T atomic_fetch_add_explicit( std::atomic<T>* obj,
                             typename std::atomic<T>::difference_type arg,

                             std::memory_order order ) noexcept;
(3) (since C++11)
template< class T >

T atomic_fetch_add_explicit( volatile std::atomic<T>* obj,
                             typename std::atomic<T>::difference_type arg,

                             std::memory_order order ) noexcept;
(4) (since C++11)

Performs atomic addition. Atomically adds arg to the value pointed to by obj and returns the value obj held previously. The operation is performed as if the following was executed:

1,2) obj->fetch_add(arg)
3,4) obj->fetch_add(arg, order)

If std::atomic<T> has no fetch_add member (this member is only provided for integral, floating-point(since C++20) and pointer types except bool), the program is ill-formed.

Contents

[edit] Parameters

obj - pointer to the atomic object to modify
arg - the value to add to the value stored in the atomic object
order - the memory synchronization ordering

[edit] Return value

The value immediately preceding the effects of this function in the modification order of *obj.

[edit] Example

Single-writer/multiple-reader lock can be made with std::atomic_fetch_add. Note that this simplistic implementation is not lockout-free.

#include <atomic>
#include <chrono>
#include <iostream>
#include <string>
#include <thread>
#include <vector>
 
using namespace std::chrono_literals;
 
// meaning of cnt:
//  5: readers and writer are in race. There are no active readers or writers.
//  4...0: there are 1...5 active readers, The writer is blocked.
// -1: writer won the race and readers are blocked.
 
const int N = 5; // four concurrent readers are allowed
std::atomic<int> cnt(N);
 
std::vector<int> data;
 
void reader(int id)
{
    for (;;)
    {
        // lock
        while (std::atomic_fetch_sub(&cnt, 1) <= 0)
            std::atomic_fetch_add(&cnt, 1);
 
        // read
        if (!data.empty())
            std::cout << ("reader " + std::to_string(id) +
                          " sees " + std::to_string(*data.rbegin()) + '\n');
        if (data.size() == 25)
            break;
 
        // unlock
        std::atomic_fetch_add(&cnt, 1);
 
        // pause
        std::this_thread::sleep_for(1ms);
    }
}
 
void writer()
{
    for (int n = 0; n < 25; ++n)
    {
        // lock
        while (std::atomic_fetch_sub(&cnt, N + 1) != N)
            std::atomic_fetch_add(&cnt, N + 1);
 
        // write
        data.push_back(n);
        std::cout << "writer pushed back " << n << '\n';
 
        // unlock
        std::atomic_fetch_add(&cnt, N + 1);
 
        // pause
        std::this_thread::sleep_for(1ms);
    }
}
 
int main()
{
    std::vector<std::thread> v;
    for (int n = 0; n < N; ++n)
        v.emplace_back(reader, n);
    v.emplace_back(writer);
 
    for (auto& t : v)
        t.join();
}

Output:

writer pushed back 0
reader 2 sees 0
reader 3 sees 0
reader 1 sees 0
<...>
reader 2 sees 24
reader 4 sees 24
reader 1 sees 24

[edit] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
P0558R1 C++11 exact type match was required because
T was deduced from multiple arguments
T is only deduced
from obj

[edit] See also

atomically adds the argument to the value stored in the atomic object and obtains the value held previously
(public member function of std::atomic<T>) [edit]
subtracts a non-atomic value from an atomic object and obtains the previous value of the atomic
(function template) [edit]
C documentation for atomic_fetch_add, atomic_fetch_add_explicit