std::atomic_fetch_and, std::atomic_fetch_and_explicit
来自 cppreference.cn
定义于头文件 <atomic> |
||
template< class T > T atomic_fetch_and( std::atomic<T>* obj, |
(1) | (C++11 起) |
template< class T > T atomic_fetch_and( volatile std::atomic<T>* obj, |
(2) | (C++11 起) |
template< class T > T atomic_fetch_and_explicit( std::atomic<T>* obj, |
(3) | (C++11 起) |
template< class T > T atomic_fetch_and_explicit( volatile std::atomic<T>* obj, |
(4) | (C++11 起) |
原子地将 obj 所指向的值替换为 obj 的旧值与 arg 进行按位 AND 运算的结果。返回 obj 先前持有的值。
该操作的执行方式等同于以下代码:
1,2) obj->fetch_and(arg)
3,4) obj->fetch_and(arg, order)
如果 std::atomic<T>
没有 fetch_and
成员(此成员仅适用于 整型,除了 bool),则程序格式不正确。
目录 |
[编辑] 参数
obj | - | 指向要修改的原子对象的指针 |
arg | - | 要与原子对象中存储的值进行按位 AND 运算的值 |
顺序 | - | 内存同步顺序 |
[编辑] 返回值
在 *obj 的修改顺序中,此函数效果之前立即的值。
[编辑] 示例
运行此代码
#include <atomic> #include <chrono> #include <functional> #include <iostream> #include <thread> // Binary semaphore for demonstrative purposes only. // This is a simple yet meaningful example: atomic operations // are unnecessary without threads. class Semaphore { std::atomic_char m_signaled; public: Semaphore(bool initial = false) { m_signaled = initial; } // Block until semaphore is signaled 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(); // signal printing to occur m_count_sem.take(); // wait until printing is complete proceeding } std::cout << "count_up() done\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() done\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() done count_up() done
[编辑] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
P0558R1 | C++11 | 因为要求精确类型匹配T 是从多个参数推导出来的 |
T 仅从来自 obj |
[编辑] 参阅
原子地在参数和原子对象的值之间执行按位与运算,并获取之前持有的值 ( std::atomic<T> 的公共成员函数) | |
(C++11)(C++11) |
将原子对象替换为与非原子参数进行位 OR 运算的结果,并获取原子的先前值 (函数模板) |
(C++11)(C++11) |
将原子对象替换为与非原子参数进行位 XOR 运算的结果,并获取原子的先前值 (函数模板) |
C 文档 用于 atomic_fetch_and, atomic_fetch_and_explicit
|