定义于头文件
<atomic>
|
||
(1) | (C++11 起) | |
template< class Integral >
Integral atomic_fetch_sub( std::atomic<Integral>* obj, Integral arg ) noexcept; |
||
template< class Integral >
Integral atomic_fetch_sub( volatile std::atomic<Integral>* obj, Integral arg ) noexcept; |
||
(2) | (C++11 起) | |
template< class Integral >
Integral atomic_fetch_sub_explicit( std::atomic<Integral>* obj, Integral arg, |
||
template< class Integral >
Integral atomic_fetch_sub_explicit( volatile std::atomic<Integral>* obj, Integral arg, |
||
(3) | (C++11 起) | |
template< class T >
T* atomic_fetch_sub( std::atomic<T*>* obj, std::ptrdiff_t arg ) noexcept; |
||
template< class T >
T* atomic_fetch_sub( volatile std::atomic<T*>* obj, std::ptrdiff_t arg ) noexcept; |
||
(4) | (C++11 起) | |
template< class T >
T* atomic_fetch_sub_explicit( std::atomic<T*>* obj, std::ptrdiff_t arg, |
||
template< class T >
T* atomic_fetch_sub_explicit( volatile std::atomic<T*>* obj, std::ptrdiff_t arg, |
||
进行原子减法。
obj
所指向的值减去 arg
,并返回 obj
先前保有的值。如同执行下列内容一样进行运算:obj
所指向的指针值 arg
,并返回 obj
先前保有的值。如同执行下列内容一样进行运算:目录 |
obj | - | 指向要修改的原子对象的指针 |
arg | - | 要从存储于原子对象的值减去的值 |
order | - | 此操作所用的内存同步顺序:容许所有值。 |
*obj
的修改顺序中立即前趋此函数效果的值。
版本一 |
---|
template< class T > typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value, T>::type atomic_fetch_sub( std::atomic<T>* obj, T arg ); { return obj->fetch_sub(arg); } |
版本二 |
template< class T > T* atomic_fetch_sub( std::atomic<T*>* obj, std::ptrdiff_t arg) { return obj->fetch_sub(arg); } |
多个线程可用 fetch_sub
同时处理有下标的容器
#include <string> #include <thread> #include <vector> #include <iostream> #include <atomic> #include <numeric> const int N = 10000; std::atomic<int> cnt; std::vector<int> data(N); void reader(int id) { for (;;) { int idx = atomic_fetch_sub_explicit(&cnt, 1, std::memory_order_relaxed); if (idx >= 0) { std::cout << "reader " << std::to_string(id) << " processed item " << std::to_string(data[idx]) << '\n'; } else { std::cout << "reader " << std::to_string(id) << " done\n"; break; } } } int main() { std::iota(data.begin(), data.end(), 1); cnt = data.size() - 1; std::vector<std::thread> v; for (int n = 0; n < 10; ++n) { v.emplace_back(reader, n); } for (auto& t : v) { t.join(); } }
输出:
reader 2 processed item 10000 reader 6 processed item 9994 reader 4 processed item 9996 reader 6 processed item 9992 <....> reader 0 done reader 5 done reader 3 done reader 9 done
原子地从存储于原子对象的值减去参数,并获得先前保有的值 ( std::atomic 的公开成员函数)
|
|
(C++11)
(C++11) |
将非原子值加到原子对象,并获得原子对象的先前值 (函数模板) |
atomic_fetch_sub, atomic_fetch_sub_explicit的 C 文档
|