std::atomic_exchange, std::atomic_exchange_explicit

定义于头文件 <atomic>
(1) (C++11 起)
template< class T >
T atomic_exchange( std::atomic<T>* obj, T desr ) noexcept;
template< class T >
T atomic_exchange( volatile std::atomic<T>* obj, T desr ) noexcept;
(2) (C++11 起)
template< class T >

T atomic_exchange_explicit( std::atomic<T>* obj, T desr,

                            std::memory_order order ) noexcept;
template< class T >

T atomic_exchange_explicit( volatile std::atomic<T>* obj, T desr,

                            std::memory_order order ) noexcept;
1) 原子地以 desr 的值替换 obj 所指向的值,并返回 obj 先前保有的值,如同以 obj->exchange(desr)
2) 原子地以 desr 的值替换 obj 所指向的值,并返回 obj 先前保有的值,如同以 obj->exchange(desr, order)

目录

参数

obj - 指向要修改的原子对象的指针
desr - 要存储于原子对象的值
order - 此操作所用的内存同步顺序:容许所有值。

返回值

obj 所指向的原子对象先前保有的值。

示例

能以原子替换操作在用户空间实现自旋锁互斥,类似 std::atomic_flag_test_and_set

#include <thread>
#include <vector>
#include <iostream>
#include <atomic>
 
std::atomic<bool> lock(false); // 锁定时保有 true
                               // 解锁时保有 false
 
void f(int n)
{
    for (int cnt = 0; cnt < 100; ++cnt) {
        while(std::atomic_exchange_explicit(&lock, true, std::memory_order_acquire))
             ; // 自旋直至获得
        std::cout << "Output from thread " << n << '\n';
        std::atomic_store_explicit(&lock, false, std::memory_order_release);
    }
}
int main()
{
    std::vector<std::thread> v;
    for (int n = 0; n < 10; ++n) {
        v.emplace_back(f, n);
    }
    for (auto& t : v) {
        t.join();
    }
}

输出:

Output from thread 2
Output from thread 6
Output from thread 7
...< 准确 1000 行 >...

参阅

原子地替换原子对象的值并获得它先前持有的值
(std::atomic 的公开成员函数)
原子地比较原子对象和非原子参数的值,若相等则进行 atomic_exchange ,若不相等则进行 atomic_load
(函数模板)
std::shared_ptr 特化原子运算
(函数模板)
atomic_exchange, atomic_exchange_explicitC 文档

版本历史

  • (当前 | 先前 2017年10月8日 (日) 09:14Fruderica讨论 | 贡献. . (2,775字节) (-978). . (撤销)
  • 当前 | 先前 2014年10月26日 (日) 16:41P12bot讨论 | 贡献 . . (3,753字节) (0). . (Fix some translations) (撤销)
  • 当前 | 先前 2013年7月2日 (二) 07:17P12bot讨论 | 贡献 . . (3,753字节) (-220). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 16:34P12bot讨论 | 贡献 . . (3,973字节) (+273). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 09:22P12讨论 | 贡献 . . (3,700字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 06:00TranslationBot讨论 | 贡献. . (3,700字节) (-77). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年10月25日 (四) 13:13P12讨论 | 贡献 . . (3,777字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (3,777字节) (+3,777). . (Translated from the English version using Google Translate)