exchange
描述 (Description)
它原子地替换原子对象的值并获得先前保存的值。
声明 (Declaration)
以下是std :: atomic :: exchange的声明。T exchange( T desired, std::memory_order order = std::memory_order_seq_cst );
C++11T exchange( T desired, std::memory_order order = std::memory_order_seq_cst ) volatile;
参数 (Parameters)desired - 用于分配值。
order - 用于强制执行内存顺序约束。
返回值 (Return Value)
它在调用之前返回原子变量的值。
异常 (Exceptions)
No-noexcept - 这个成员函数永远不会抛出异常。
例子 (Example)
在下面的示例中为std :: atomic :: exchange。#include
#include
#include
#include
std::atomic ready (false);
std::atomic winner (false);
void count1m (int id) {
while (!ready) {}
for (int i=0; i<1000000; ++i) {}
if (!winner.exchange(true)) { std::cout << "thread #" << id << " won!\n"; }
};
int main () {
std::vector<:thread> threads;
std::cout << "spawning 10 threads that count to 1 million...\n";
for (int i=1; i<=10; ++i) threads.push_back(std::thread(count1m,i));
ready = true;
for (auto& th : threads) th.join();
return 0;
}