Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/atomic/atomic compare exchange"

From cppreference.com
< cpp‎ | atomic
(+)
 
(Applied P2869R4 (Remove Deprecated shared_ptr Atomic Access APIs from C++26).)
 
(42 intermediate revisions by 13 users not shown)
Line 1: Line 1:
 
{{cpp/title|atomic_compare_exchange_weak|atomic_compare_exchange_strong|atomic_compare_exchange_weak_explicit|atomic_compare_exchange_strong_explicit}}
 
{{cpp/title|atomic_compare_exchange_weak|atomic_compare_exchange_strong|atomic_compare_exchange_weak_explicit|atomic_compare_exchange_strong_explicit}}
{{cpp/atomic/sidebar}}
+
{{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 T >
 
template< class T >
bool atomic_compare_exchange_weak(std::atomic<T>* obj, T* exp, T desr)
+
bool atomic_compare_exchange_weak
 +
    ( std::atomic<T>* obj, typename std::atomic<T>::value_type* expected,
 +
      typename std::atomic<T>::value_type desired ) noexcept;
 
}}
 
}}
{{ddcl list item | num=2 | notes={{mark since c++11}} | 1=
+
{{dcl|num=2|since=c++11|
 
template< class T >
 
template< class T >
bool atomic_compare_exchange_weak(volatile std::atomic<T>* obj, T* exp, T desr)
+
bool atomic_compare_exchange_weak
 +
    ( volatile std::atomic<T>* obj,
 +
      typename std::atomic<T>::value_type* expected,
 +
      typename std::atomic<T>::value_type desired ) noexcept;
 
}}
 
}}
{{ddcl list item | num=3 | notes={{mark since c++11}} | 1=
+
{{dcl|num=3|since=c++11|
 
template< class T >
 
template< class T >
bool atomic_compare_exchange_strong(std::atomic<T>* obj, T* exp, T desr)
+
bool atomic_compare_exchange_strong
 +
    ( std::atomic<T>* obj, typename std::atomic<T>::value_type* expected,
 +
      typename std::atomic<T>::value_type desired ) noexcept;
 
}}
 
}}
{{ddcl list item | num=4 | notes={{mark since c++11}} | 1=
+
{{dcl|num=4|since=c++11|
 
template< class T >
 
template< class T >
bool atomic_compare_exchange_strong(volatile std::atomic<T>* obj, T* exp, T desr)
+
bool atomic_compare_exchange_strong
 +
    ( volatile std::atomic<T>* obj,
 +
      typename std::atomic<T>::value_type* expected,  
 +
      typename std::atomic<T>::value_type desired ) noexcept;
 
}}
 
}}
 
+
{{dcl|num=5|since=c++11|
{{ddcl list item | num=5 | notes={{mark since c++11}} | 1=
+
 
template< class T >
 
template< class T >
bool atomic_compare_exchange_weak_explicit(std::atomic<T>* obj, T* exp, T desr,
+
bool atomic_compare_exchange_weak_explicit
                                          std::memory_order succ, std::memory_order fail)
+
    ( std::atomic<T>* obj, typename std::atomic<T>::value_type* expected,  
 +
      typename std::atomic<T>::value_type desired,
 +
      std::memory_order success, std::memory_order failure ) noexcept;
 
}}
 
}}
{{ddcl list item | num=6 | notes={{mark since c++11}} | 1=
+
{{dcl|num=6|since=c++11|
 
template< class T >
 
template< class T >
bool atomic_compare_exchange_weak_explicit(volatile std::atomic<T>* obj, T* exp, T desr,
+
bool atomic_compare_exchange_weak_explicit
                                          std::memory_order succ, std::memory_order fail)
+
    ( volatile std::atomic<T>* obj,
 +
      typename std::atomic<T>::value_type* expected,  
 +
      typename std::atomic<T>::value_type desired,
 +
      std::memory_order success, std::memory_order failure ) noexcept;
 
}}
 
}}
 
+
{{dcl|num=7|since=c++11|
{{ddcl list item | num=7 | notes={{mark since c++11}} | 1=
+
 
template< class T >
 
template< class T >
bool atomic_compare_exchange_strong(std::atomic<T>* obj, T* exp, T desr,
+
bool atomic_compare_exchange_strong_explicit
                                    std::memory_order succ, std::memory_order fail)
+
    ( std::atomic<T>* obj, typename std::atomic<T>::value_type* expected,  
 +
      typename std::atomic<T>::value_type desired,
 +
      std::memory_order success, std::memory_order failure ) noexcept;
 
}}
 
}}
{{ddcl list item | num=8 | notes={{mark since c++11}} | 1=
+
{{dcl|num=8|since=c++11|
 
template< class T >
 
template< class T >
bool atomic_compare_exchange_strong(volatile std::atomic<T>* obj, T* exp, T desr,
+
bool atomic_compare_exchange_strong_explicit
                                    std::memory_order succ, std::memory_order fail)
+
    ( volatile std::atomic<T>* obj,
 +
      typename std::atomic<T>::value_type* expected,  
 +
      typename std::atomic<T>::value_type desired,
 +
      std::memory_order success, std::memory_order failure ) noexcept;
 
}}
 
}}
{{ddcl list end}}
+
{{dcl end}}
  
In a single atomic operation, first compares the value pointed to by {{tt|obj}} with the value pointed to by {{tt|exp}} for equality. Then, if the values are equal, replaces the value pointed to by {{tt|obj}} with the value of {{tt|desr}} (performs a read-modify-write operation). Otherwise, if the values are not equal, replaces the value pointed to by {{tt|exp}} with the value of {{tt|obj}} (performs a load operation), using the memory model {{tt|fail}}
+
Atomically compares the {{rev inl|until=c++20|[[cpp/language/object|object representation]]}}{{rev inl|since=c++20|[[cpp/language/object|value representation]]}} of the object pointed to by {{c|obj}} with that of the object pointed to by {{c|expected}}, and if those are bitwise-equal, replaces the former with {{c|desired}} (performs read-modify-write operation). Otherwise, loads the actual value pointed to by {{c|obj}} into {{c|*expected}} (performs load operation).
  
1,2,5,6) The weak form of this function is allowed to fail spuriously, that is, return {{cpp|false}} and perform the load from *obj to *exp even if {{cpp|1=*obj == *exp}}. When a compare-and-exchange is in a loop, the weak version will yield better performance on some platforms. When a weak compare-and-exchange would require a loop and a strong one would not, the strong one is preferable.
+
{|class="wikitable" style="text-align: center;"
 +
!rowspan=2|{{nbsp}}Overloads{{nbsp}}
 +
!colspan=2|Memory model for
 +
|-
 +
!{{nbsp}}read&#8209;modify&#8209;write{{nbsp}}operation{{nbsp}}
 +
!load operation
 +
|-
 +
|{{v|1-4}}
 +
|{{c|std::memory_order_seq_cst}}
 +
|{{nbsp}}{{c|std::memory_order_seq_cst}}{{nbsp}}
 +
|-
 +
|{{v|5-8}}
 +
|{{c|success}}
 +
|{{c|failure}}
 +
|}
  
These functions are defined in terms of member functions of {{cpp|std::atomic}}:
+
These functions are defined in terms of [[cpp/atomic/atomic/compare_exchange|member functions]] of {{lc|std::atomic}}:
 +
@1,2@ {{c|obj->compare_exchange_weak(*expected, desired)}}
 +
@3,4@ {{c|obj->compare_exchange_strong(*expected, desired)}}
 +
@5,6@ {{c|obj->compare_exchange_weak(*expected, desired, success, failure)}}
 +
@7,8@ {{c|obj->compare_exchange_strong(*expected, desired, success, failure)}}
  
1-2) {{cpp|obj->compare_exhange_weak(exp, desr)}}
+
If {{c|failure}}{{rev inl|until=c++17| is stronger than {{c|success}} or}} is one of {{c|std::memory_order_release}} and {{c|std::memory_order_acq_rel}}, the behavior is undefined.
  
3-4) {{cpp|obj->compare_exhange_strong(exp, desr)}}
+
===Parameters===
 +
{{par begin}}
 +
{{par|obj|pointer to the atomic object to test and modify}}
 +
{{par|expected|pointer to the value expected to be found in the atomic object}}
 +
{{par|desired|the value to store in the atomic object if it is as expected}}
 +
{{par|success|the memory synchronization ordering for the read-modify-write operation if the comparison succeeds}}
 +
{{par|failure|the memory synchronization ordering for the load operation if the comparison fails}}
 +
{{par end}}  
  
5-6) {{cpp|obj->compare_exhange_weak(exp, desr, succ, fail)}}
+
===Return value===
 +
The result of the comparison: {{c|true}} if {{c|*obj}} was equal to {{c|*expected}}, {{c|false}} otherwise.
  
7-8) {{cpp|obj->compare_exhange_strong(exp, desr, succ, fail)}}
+
===Notes===
 +
{{tt|std::atomic_compare_exchange_weak}} and {{tt|std::atomic_compare_exchange_weak_explicit}} (the weak versions) are allowed to fail spuriously, that is, act as if {{c|1=*obj != *expected}} even if they are equal. When a compare-and-exchange is in a loop, they will yield better performance on some platforms.
  
 +
When a weak compare-and-exchange would require a loop and a strong one would not, the strong one is preferable unless the object representation of {{tt|T}} may include {{rev inl|until=c++20|padding bits,}} trap bits, or offers multiple object representations for the same value (e.g. floating-point NaN). In those cases, weak compare-and-exchange typically works because it quickly converges on some stable object representation.
  
===Parameters===
+
For a union with bits that participate in the value representations of some members but not the others, compare-and-exchange might always fail because such padding bits have indeterminate values when they do not participate in the value representation of the active member.
  
{{param list begin}}
+
{{rrev|since=c++20|1=
{{param list item | obj | pointer to the atomic object to test and modify}}
+
Padding bits that never participate in an object's value representation are ignored.
{{param list item | exp | pointer to the value expected to be found in the atomic object}}
+
}}
{{param list item | desr | the value to store in the atomic object if it is as expected}}
+
{{param list item | succ | the memory sycnhronization ordering for this operation. All values are permitted. }}
+
{{param list item | fail | the memory sycnhronization ordering for this operation. Cannot be {{cpp|std::memory_order_release}} or {{cpp|std::memory_order_ack_rel}} and cannot specify stronger ordering than {{tt|succ}}}}
+
{{param list end}}  
+
  
===Return value===
+
===Example===
The result of the comparison: {{cpp|true}} if *obj was equal to *exp, {{cpp|false}} otherwise.
+
{{example
 +
|Compare and exchange operations are often used as basic building blocks of lockfree data structures.
 +
|code=
 +
#include <atomic>
  
===Exceptions===
+
template<class T>
{{noexcept}}
+
struct node
 +
{
 +
    T data;
 +
    node* next;
 +
    node(const T& data) : data(data), next(nullptr) {}
 +
};
  
===Example===
+
template<class T>
{{example cpp
+
class stack
| This example shows how compare-and-exchange may be used to implement lock-free append to a singly linked list
+
| code=
+
void append(list* s, node* n)
+
 
{
 
{
     node* head;
+
     std::atomic<node<T>*> head;
     do
+
public:
 +
     void push(const T& data)
 
     {
 
     {
         head = s->head;
+
         node<T>* new_node = new node<T>(data);
         n->next = head;
+
       
 +
        // put the current value of head into new_node->next
 +
        new_node->next = head.load(std::memory_order_relaxed);
 +
          
 +
        // now make new_node the new head, but if the head
 +
        // is no longer what's stored in new_node->next
 +
        // (some other thread must have inserted a node just now)
 +
        // then put that new head into new_node->next and try again
 +
        while (!std::atomic_compare_exchange_weak_explicit(
 +
                  &head, &new_node->next, new_node,
 +
                  std::memory_order_release, std::memory_order_relaxed))
 +
            ; // the body of the loop is empty
 +
// note: the above loop is not thread-safe in at least
 +
// GCC prior to 4.8.3 (bug 60272), clang prior to 2014-05-05 (bug 18899)
 +
// MSVC prior to 2014-03-17 (bug 819819). See member function version for workaround
 
     }
 
     }
     while ( ! std::atomic_compare_exchange_weak(s->head, head, n));
+
};
 +
 
 +
int main()
 +
{
 +
     stack<int> s;
 +
    s.push(1);
 +
    s.push(2);
 +
    s.push(3);
 
}
 
}
  | output=
 
 
}}
 
}}
 +
 +
===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 compare_exchange | mem=std::atomic<T>}}
+
{{dsc inc|cpp/atomic/atomic/dsc compare_exchange}}
{{dcl list template | cpp/atomic/dcl list atomic_exchange}}
+
{{dsc inc|cpp/atomic/dsc atomic_exchange}}
{{dcl list tfun | cpp/memory/shared_ptr/atomic_access | title=std::atomic_compare_exchange_weak{{dcl small|(std::shared_ptr)}}
+
{{dsc break}}
<br>std::atomic_compare_exchange_strong{{dcl small|(std::shared_ptr)}} | specializes atomic operations for std::shared_ptr }}
+
{{dsc tfun|cpp/memory/shared_ptr/atomic|notes={{mark life|deprecated=c++20|removed=c++26|br=yes}}|title=std::atomic_compare_exchange_weak{{dsc small|(std::shared_ptr)}}
{{dcl list end}}
+
<br>std::atomic_compare_exchange_strong{{dsc small|(std::shared_ptr)}}|specializes atomic operations for std::shared_ptr}}
 +
{{dsc see c|c/atomic/atomic_compare_exchange|atomic_compare_exchange|atomic_compare_exchange_explicit}}
 +
{{dsc end}}
 +
 
 +
{{langlinks|de|es|fr|it|ja|pt|ru|zh}}

Latest revision as of 05:26, 24 April 2024

 
 
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_compare_exchange_weakatomic_compare_exchange_weak_explicitatomic_compare_exchange_strongatomic_compare_exchange_strong_explicit
(C++11)(C++11)(C++11)(C++11)
Free functions for atomic flags
 
Defined in header <atomic>
template< class T >

bool atomic_compare_exchange_weak
    ( std::atomic<T>* obj, typename std::atomic<T>::value_type* expected,

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

bool atomic_compare_exchange_weak
    ( volatile std::atomic<T>* obj,
      typename std::atomic<T>::value_type* expected,

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

bool atomic_compare_exchange_strong
    ( std::atomic<T>* obj, typename std::atomic<T>::value_type* expected,

      typename std::atomic<T>::value_type desired ) noexcept;
(3) (since C++11)
template< class T >

bool atomic_compare_exchange_strong
    ( volatile std::atomic<T>* obj,
      typename std::atomic<T>::value_type* expected,

      typename std::atomic<T>::value_type desired ) noexcept;
(4) (since C++11)
template< class T >

bool atomic_compare_exchange_weak_explicit
    ( std::atomic<T>* obj, typename std::atomic<T>::value_type* expected,
      typename std::atomic<T>::value_type desired,

      std::memory_order success, std::memory_order failure ) noexcept;
(5) (since C++11)
template< class T >

bool atomic_compare_exchange_weak_explicit
    ( volatile std::atomic<T>* obj,
      typename std::atomic<T>::value_type* expected,
      typename std::atomic<T>::value_type desired,

      std::memory_order success, std::memory_order failure ) noexcept;
(6) (since C++11)
template< class T >

bool atomic_compare_exchange_strong_explicit
    ( std::atomic<T>* obj, typename std::atomic<T>::value_type* expected,
      typename std::atomic<T>::value_type desired,

      std::memory_order success, std::memory_order failure ) noexcept;
(7) (since C++11)
template< class T >

bool atomic_compare_exchange_strong_explicit
    ( volatile std::atomic<T>* obj,
      typename std::atomic<T>::value_type* expected,
      typename std::atomic<T>::value_type desired,

      std::memory_order success, std::memory_order failure ) noexcept;
(8) (since C++11)

Atomically compares the object representation(until C++20)value representation(since C++20) of the object pointed to by obj with that of the object pointed to by expected, and if those are bitwise-equal, replaces the former with desired (performs read-modify-write operation). Otherwise, loads the actual value pointed to by obj into *expected (performs load operation).

 Overloads  Memory model for
 read‑modify‑write operation  load operation
(1-4) std::memory_order_seq_cst  std::memory_order_seq_cst 
(5-8) success failure

These functions are defined in terms of member functions of std::atomic:

1,2) obj->compare_exchange_weak(*expected, desired)
3,4) obj->compare_exchange_strong(*expected, desired)
5,6) obj->compare_exchange_weak(*expected, desired, success, failure)
7,8) obj->compare_exchange_strong(*expected, desired, success, failure)

If failure is stronger than success or(until C++17) is one of std::memory_order_release and std::memory_order_acq_rel, the behavior is undefined.

Contents

[edit] Parameters

obj - pointer to the atomic object to test and modify
expected - pointer to the value expected to be found in the atomic object
desired - the value to store in the atomic object if it is as expected
success - the memory synchronization ordering for the read-modify-write operation if the comparison succeeds
failure - the memory synchronization ordering for the load operation if the comparison fails

[edit] Return value

The result of the comparison: true if *obj was equal to *expected, false otherwise.

[edit] Notes

std::atomic_compare_exchange_weak and std::atomic_compare_exchange_weak_explicit (the weak versions) are allowed to fail spuriously, that is, act as if *obj != *expected even if they are equal. When a compare-and-exchange is in a loop, they will yield better performance on some platforms.

When a weak compare-and-exchange would require a loop and a strong one would not, the strong one is preferable unless the object representation of T may include padding bits,(until C++20) trap bits, or offers multiple object representations for the same value (e.g. floating-point NaN). In those cases, weak compare-and-exchange typically works because it quickly converges on some stable object representation.

For a union with bits that participate in the value representations of some members but not the others, compare-and-exchange might always fail because such padding bits have indeterminate values when they do not participate in the value representation of the active member.

Padding bits that never participate in an object's value representation are ignored.

(since C++20)

[edit] Example

Compare and exchange operations are often used as basic building blocks of lockfree data structures.

#include <atomic>
 
template<class T>
struct node
{
    T data;
    node* next;
    node(const T& data) : data(data), next(nullptr) {}
};
 
template<class T>
class stack
{
    std::atomic<node<T>*> head;
public:
    void push(const T& data)
    {
        node<T>* new_node = new node<T>(data);
 
        // put the current value of head into new_node->next
        new_node->next = head.load(std::memory_order_relaxed);
 
        // now make new_node the new head, but if the head
        // is no longer what's stored in new_node->next
        // (some other thread must have inserted a node just now)
        // then put that new head into new_node->next and try again
        while (!std::atomic_compare_exchange_weak_explicit(
                   &head, &new_node->next, new_node,
                   std::memory_order_release, std::memory_order_relaxed))
            ; // the body of the loop is empty
// note: the above loop is not thread-safe in at least
// GCC prior to 4.8.3 (bug 60272), clang prior to 2014-05-05 (bug 18899)
// MSVC prior to 2014-03-17 (bug 819819). See member function version for workaround
    }
};
 
int main()
{
    stack<int> s;
    s.push(1);
    s.push(2);
    s.push(3);
}

[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 compares the value of the atomic object with non-atomic argument and performs atomic exchange if equal or atomic load if not
(public member function of std::atomic<T>) [edit]
atomically replaces the value of the atomic object with non-atomic argument and returns the old value of the atomic
(function template) [edit]
specializes atomic operations for std::shared_ptr
(function template)
C documentation for atomic_compare_exchange, atomic_compare_exchange_explicit