yohhoyの日記

技術的メモをしていきたい日記

volatile版atomic操作関数が存在する理由

C++11標準ライブラリのatomic変数において、操作関数にvolatile非修飾/修飾版の2種類が提供される理由。

volatile変数とatomic変数は直交する概念であり、単に「volatileオブジェクトに対してもatomic操作を提供するため」に追加されている。*1

2021-04-21追記:C++20ではP1831R1が採択され、ロックフリー性が保証されないatomic変数型におけるvolatile修飾版メンバ関数オーバーロードは非推奨化された。

atomicクラステンプレートおよび関連する非メンバ関数の宣言を引用(一部は簡略化)。

template <class T> struct atomic {
  void store(T) volatile noexcept;
  void store(T) noexcept;
  T load() const volatile noexcept;
  T load() const noexcept;
  //...
};

void atomic_store(volatile atomic<T> *, T) noexcept;
void atomic_store(atomic<T> *, T) noexcept;
T atomic_load(const volatile atomic<T> *) noexcept;
T atomic_load(const atomic<T> *) noexcept;
//...

N3337 29.6.5/p3に理由が記載されている。

[Note: Many operations are volatile-qualified. The "volatile as device register" semantics have not changed in the standard. This qualification means that volatility is preserved when applying these operations to volatile objects. It does not mean that operations on non-volatile objects become volatile. Thus, volatile qualified operations on non-volatile objects may be merged under some conditions. -- end note]

The functions and operations are defined to work with volatile objects, so that variables that should be volatile can also be atomic. The volatile qualifier, however, is not required for atomicity.

http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2007/n2324.html#Summary

関連URL

*1:volatile修飾は従来どおり “C++規格が関知しない外部へアクセスされ得る” という意味しかなく、C++規格の範疇ではマルチスレッド並行処理における変数操作のアトミック性とは無関係。