public member function
<atomic>

std::atomic::exchange

T exchange (T val, memory_order sync = memory_order_seq_cst) volatile noexcept;T exchange (T val, memory_order sync = memory_order_seq_cst) noexcept;
訪問並修改包含的值
val 替換為包含的值,並返回它之前的值。

整個操作是原子的(一個原子讀-修改-寫操作):在函式讀取(並返回)其值到修改其值的時刻之間,該值不會受到其他執行緒的影響。

引數

val
要複製到包含物件的值。
Tatomic 的模板引數(包含值的型別)。
sync
操作的同步模式。
可以是 enum 型別 memory_order 的任何可能值
memory order描述
memory_order_relaxedRelaxed無副作用同步。
memory_order_consumeConsume同步來自最後一個releasesequentially consistent 操作的帶有依賴關係的值的可見副作用。
memory_order_acquireAcquire同步來自最後一個releasesequentially consistent 操作的所有可見副作用。
memory_order_releaseRelease將副作用與下一個consumeacquire 操作同步。
memory_order_acq_relAcquire/Release讀取為acquire 操作,寫入為release 操作(如上所述)。
memory_order_seq_cstSequentially consistent將所有可見的副作用與其他的sequentially consistent 操作同步,遵循單一的全域性順序。

返回值

呼叫前的儲存值。
Tatomic 的模板引數(包含值的型別)。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// atomic::exchange example
#include <iostream>       // std::cout
#include <atomic>         // std::atomic
#include <thread>         // std::thread
#include <vector>         // std::vector

std::atomic<bool> ready (false);
std::atomic<bool> winner (false);

void count1m (int id) {
  while (!ready) {}                  // wait for the ready signal
  for (int i=0; i<1000000; ++i) {}   // go!, count to 1 million
  if (!winner.exchange(true)) { std::cout << "thread #" << id << " won!\n"; }
};

int main ()
{
  std::vector<std::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;
}

可能的輸出(其他執行緒可能獲勝)
spawning 10 threads that count to 1 million...
thread #7 won!


資料競爭

無資料競爭(原子操作)。記憶體順序由引數 sync 指定。

異常安全

無異常保證: 絕不丟擲異常。

另見