std::atomic_fetch_and, std::atomic_fetch_and_explicit
来自cppreference.com
<tbody>
</tbody>
| 在标头 <atomic> 定义
|
||
template< class T > T atomic_fetch_and( std::atomic<T>* obj, typename std::atomic<T>::value_type arg ) noexcept; |
(1) | (C++11 起) |
template< class T > T atomic_fetch_and( volatile std::atomic<T>* obj, typename std::atomic<T>::value_type arg ) noexcept; |
(2) | (C++11 起) |
template< class T > T atomic_fetch_and_explicit( std::atomic<T>* obj, typename std::atomic<T>::value_type arg, std::memory_order order ) noexcept; |
(3) | (C++11 起) |
template< class T > T atomic_fetch_and_explicit( volatile std::atomic<T>* obj, typename std::atomic<T>::value_type arg, std::memory_order order ) noexcept; |
(4) | (C++11 起) |
以 obj 的旧值和 arg 的逐位与结果原子地替换 obj 所指向的值。返回 obj 先前保有的值。
如同执行下列内容一般进行操作:
1,2)
obj->fetch_and(arg)3,4)
obj->fetch_and(arg, order)如果 std::atomic<T> 没有 fetch_and 成员(此成员仅对 bool 以外的整数类型提供),那么程序非良构。
参数
| obj | - | 指向要修改的对象的指针 |
| arg | - | 与存储于原子对象的值逐位与的值 |
| order | - | 内存同步定序 |
返回值
*obj 的修改顺序中,紧接此函数生效之前的值。
示例
运行此代码
#include <atomic>
#include <chrono>
#include <functional>
#include <iostream>
#include <thread>
// 仅为演示目的的二值信号量
// 此乃简单却有意义的示例:如果不使用线程,那么也不需要原子操作。
class Semaphore
{
std::atomic_char m_signaled;
public:
Semaphore(bool initial = false)
{
m_signaled = initial;
}
// 阻塞到信号量被发信
void take()
{
while (!std::atomic_fetch_and(&m_signaled, false))
{
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
void put()
{
std::atomic_fetch_or(&m_signaled, true);
}
};
class ThreadedCounter
{
static const int N = 100;
static const int REPORT_INTERVAL = 10;
int m_count;
bool m_done;
Semaphore m_count_sem;
Semaphore m_print_sem;
void count_up()
{
for (m_count = 1; m_count <= N; ++m_count)
if (m_count % REPORT_INTERVAL == 0)
{
if (m_count == N)
m_done = true;
m_print_sem.put(); // 对打印发信,使之发生
m_count_sem.take(); // 等待直至打印完成进展
}
std::cout << "count_up() 完成\n";
m_done = true;
m_print_sem.put();
}
void print_count()
{
do
{
m_print_sem.take();
std::cout << m_count << '\n';
m_count_sem.put();
}
while (!m_done);
std::cout << "print_count() 完成\n";
}
public:
ThreadedCounter() : m_done(false) {}
void run()
{
auto print_thread = std::thread(&ThreadedCounter::print_count, this);
auto count_thread = std::thread(&ThreadedCounter::count_up, this);
print_thread.join();
count_thread.join();
}
};
int main()
{
ThreadedCounter m_counter;
m_counter.run();
}
输出:
10
20
30
40
50
60
70
80
90
100
print_count() 完成
count_up() 完成
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| P0558R1 | C++11 | 要求准确类型匹配,因为会从多个参数推导 T
|
只会从 obj 推导 T
|
参阅
| 原子地进行实参和原子对象的值的逐位与,并获得先前保有的值 ( std::atomic<T> 的公开成员函数)
| |
(C++11)(C++11) |
将原子对象替换为与非原子实参逐位或的结果,并获得原子对象的先前值 (函数模板) |
(C++11)(C++11) |
将原子对象替换为与非原子实参逐位异或的结果,并获得原子对象的先前值 (函数模板) |
atomic_fetch_and, atomic_fetch_and_explicit 的 C 文档
| |