std::atomic_exchange, std::atomic_exchange_explicit
来自cppreference.com
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
在头文件 <atomic> 中定义
|
||
template< class T > T atomic_exchange( std::atomic<T>* obj, T desr ); |
(1) | (C++11 起) |
template< class T > T atomic_exchange( volatile std::atomic<T>* obj, T desr ); |
(2) | (C++11 起) |
template< class T > T atomic_exchange_explicit( std::atomic<T>* obj, T desr, |
(3) | (C++11 起) |
template< class T > T atomic_exchange_explicit( volatile std::atomic<T>* obj, T desr, |
(4) | (C++11 起) |
原子取代
3-4) obj
desr
的价值指向的值,并返回以前举行的价值obj
,如果由obj->exhange(desr)原文:
Atomically replaces the value pointed to by
obj
with the value of desr
and returns the value obj
held previously, as if by obj->exhange(desr)原子取代
obj
desr
的价值指向的值,并返回以前举行的价值obj
,如果由obj->exhange(desr, order)原文:
Atomically replaces the value pointed to by
obj
with the value of desr
and returns the value obj
held previously, as if by obj->exhange(desr, order)目录 |
[编辑] 参数
obj | - | 指针的原子对象修改
原文: pointer to the atomic object to modify |
desr | - | 要存储的值在原子的对象
原文: the value to store in the atomic object |
order | - | 的的内存sycnhronization订购此操作:所有的允许值.
原文: the memory sycnhronization ordering for this operation: all values are permitted. |
[编辑] 返回值
以前保存的值的原子对象所指向的
obj
原文:
The value held previously by the atomic object pointed to by
obj
[编辑] 例外
[编辑] 示例
一个自旋锁互斥体可以使用一个原子交换操作,类似atomic_flag_test_and_set的的在用户空间中实现
原文:
A spinlock mutex can be implemented in userspace using an atomic exchange operation, similar to atomic_flag_test_and_set
#include <thread> #include <vector> #include <iostream> #include <atomic> std::atomic<bool> lock = ATOMIC_VAR_INIT(false); void f(int n) { for(int cnt = 0; cnt < 100; ++cnt) { while(std::atomic_exchange_explicit(&lock, true, std::memory_order_acquire)) ; // spin until acquired 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 ...<exactly 1000 lines>...
[编辑] 另请参阅
(C++11) |
原子取代原子对象的值,并获得先前保持的值 原文: atomically replaced the value of the atomic object and obtains the value held previously (公共成员函数of std::atomic )
|
原子原子对象与非原子的参数的值的比较,并执行原子交换,如果等于或原子的负载如果不是 原文: atomically compares the value of the atomic object with non-atomic argument and performs atomic exchange if equal or atomic load if not (函数模板) | |
专业的原子操作,std::shared_ptr 原文: specializes atomic operations for std::shared_ptr (函数模板) | |
C documentation for atomic_exchange, atomic_exchange_explicit
|