Namespaces
Variants
Views
Actions

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

From cppreference.com
< cpp‎ | atomic
m (Text replace - "/sidebar" to "/navbar")
m (Return value: #)
 
(28 intermediate revisions by 12 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}}
{{ddcl list begin}}
+
{{dcl begin}}
{{ddcl list header | atomic }}
+
{{dcl header|atomic}}
{{ddcl list item | num=1 | notes={{mark since c++11}} | 1=
+
{{dcl|num=1|since=c++11|
template< class Integral >
+
Integral atomic_fetch_add( std::atomic<Integral>* obj, Integral arg );
+
}}
+
{{ddcl list item | num=2 | notes={{mark since c++11}} | 1=
+
template< class Integral >
+
Integral atomic_fetch_add( volatile std::atomic<Integral>* obj, Integral arg );
+
}}
+
{{ddcl list item | num=3 | notes={{mark since c++11}} | 1=
+
template< class Integral >
+
Integral atomic_fetch_add_explicit( std::atomic<Integral>* obj, Integral arg,
+
                                    std::memory_order order );
+
}}
+
{{ddcl list item | num=4 | notes={{mark since c++11}} | 1=
+
template< class Integral >
+
Integral atomic_fetch_add_explicit( volatile std::atomic<Integral>* obj, Integral arg,
+
                                    std::memory_order order );
+
}}
+
{{ddcl list item | num=5 | notes={{mark since c++11}} | 1=
+
 
template< class T >
 
template< class T >
T* atomic_fetch_add( std::atomic<T*>* obj, std::ptrdiff_t arg );
+
T atomic_fetch_add( std::atomic<T>* obj,
 +
                    typename std::atomic<T>::difference_type arg ) noexcept;
 
}}
 
}}
{{ddcl list item | num=6 | notes={{mark since c++11}} | 1=
+
{{dcl|num=2|since=c++11|
 
template< class T >
 
template< class T >
T* atomic_fetch_add( volatile std::atomic<T*>* obj, std::ptrdiff_t arg );
+
T atomic_fetch_add( volatile std::atomic<T>* obj,
 +
                    typename std::atomic<T>::difference_type arg ) noexcept;
 
}}
 
}}
{{ddcl list item | num=7 | notes={{mark since c++11}} | 1=
+
{{dcl|num=3|since=c++11|
 
template< class T >
 
template< class T >
T* atomic_fetch_add_explicit( std::atomic<T*>* obj, std::ptrdiff_t arg,  
+
T atomic_fetch_add_explicit( std::atomic<T>* obj,
                              std::memory_order order );
+
                            typename std::atomic<T>::difference_type arg,
 +
                            std::memory_order order ) noexcept;
 
}}
 
}}
{{ddcl list item | num=8 | notes={{mark since c++11}} | 1=
+
{{dcl|num=4|since=c++11|
 
template< class T >
 
template< class T >
T* atomic_fetch_add_explicit( volatile std::atomic<T*>* obj, std::ptrdiff_t arg,  
+
T atomic_fetch_add_explicit( volatile std::atomic<T>* obj,
                              std::memory_order order );
+
                            typename std::atomic<T>::difference_type arg,
 +
                            std::memory_order order ) noexcept;
 
}}
 
}}
{{ddcl list end}}
+
{{dcl end}}
  
1-2) Atomically adds {{tt|arg}} to the value pointed to by {{tt|obj}} and returns the value {{tt|obj}} held previously, as if by {{c|obj->fetch_add(arg)}}
+
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)}}
  
3-4) Atomically adds {{tt|arg}} to the value pointed to by {{tt|obj}} and returns the value {{tt|obj}} held previously, as if by {{c|obj->fetch_add(arg, order)}}
+
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.
 
+
5-6) Atomically increments the pointer value, pointed to by {{tt|obj}}, by {{tt|arg}}, and returns the value {{tt|obj}} held previously, as if by {{c|obj->fetch_add(arg)}}
+
 
+
7-8) Atomically increments the pointer value, pointed to by {{tt|obj}}, by {{tt|arg}}, and returns the value {{tt|obj}} held previously, as if by {{c|obj->fetch_add(arg, order)}}
+
  
 
===Parameters===
 
===Parameters===
 
+
{{par begin}}
{{param list begin}}
+
{{par|obj|pointer to the atomic object to modify}}
{{param list item | obj | pointer to the atomic object to modify}}
+
{{par|arg|the value to add to the value stored in the atomic object}}
{{param list item | arg | the value to add to the value stored in the atomic object}}
+
{{par|order|the memory synchronization ordering}}
{{param list item | order | the memory sycnhronization ordering for this operation: all values are permitted.}}
+
{{par end}}
{{param list end}}  
+
  
 
===Return value===
 
===Return value===
The value held previously by the atomic object pointed to by {{tt|obj}}
+
The value immediately preceding the effects of this function in the {{lsd|cpp/atomic/memory order#Modification order}} of {{c|*obj}}.
 
+
===Exceptions===
+
{{noexcept}}
+
 
+
===Possible implementation===
+
{{eq fun cpp
+
| 1=
+
template< class T >
+
typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value, T>::type
+
atomic_fetch_add( std::atomic<T>* obj, T arg );
+
{
+
    return obj->fetch_add(arg);
+
}
+
| 2=
+
template< class T >
+
T* atomic_fetch_add( std::atomic<T*>* obj, std::ptrdiff_t 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:
// 10: there are no active readers or writers.
+
// 5: readers and writer are in race. There are no active readers or writers.
// 1...9: there are 9...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 = 10; // nine concurrent readers are allowed
+
const int N = 5; // four concurrent readers are allowed
std::atomic<int> cnt = ATOMIC_VAR_INIT(N);
+
std::atomic<int> cnt(N);
  
 
std::vector<int> data;
 
std::vector<int> data;
Line 103: 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() == 100)
+
         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 123: Line 91:
 
void writer()
 
void writer()
 
{
 
{
     for(int n = 0; n < 100; ++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 141: 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 8 sees 0
+
reader 2 sees 0
 
reader 3 sees 0
 
reader 3 sees 0
 
reader 1 sees 0
 
reader 1 sees 0
 
<...>
 
<...>
reader 2 sees 99
+
reader 2 sees 24
reader 6 sees 99
+
reader 4 sees 24
reader 1 sees 99
+
reader 1 sees 24
 
}}
 
}}
 +
 +
===Defect reports===
 +
{{dr list begin}}
 +
{{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}}
  
 
===See also===
 
===See also===
{{dcl list begin}}
+
{{dsc begin}}
{{dcl list template | cpp/atomic/atomic/dcl list fetch_add | mem=std::atomic<T>}}
+
{{dsc inc|cpp/atomic/atomic/dsc fetch_add}}
{{dcl list template | cpp/atomic/dcl list atomic_fetch_sub}}
+
{{dsc inc|cpp/atomic/dsc atomic_fetch_sub}}
{{dcl list end}}
+
{{dsc see c|c/atomic/atomic_fetch_add|atomic_fetch_add|atomic_fetch_add_explicit}}
 +
{{dsc end}}
 +
 
 +
{{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