yohhoyの日記

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

vector要素アクセスとスレッド安全性

前記事のサンプルコード(下記)を書いた時に、“複数スレッドから同じstd::vector<T>上の異なる要素へ同時アクセス” のスレッド安全性が気になったのでメモ。

#include <vector>
#include "tbb/compat/ppl.h"

std::vector<int> data = /*...*/;

// 全ての要素値を2倍する
Concurrency::parallel_for_each(
  data.begin(), data.end(),
  [](int& x){ x *= 2; }
);

N3290を確認したところ、23.2.2 Container data races/p2-3に下記の通り定義&例示があった。

2. Notwithstanding (17.6.5.9), implementations are required to avoid data races when the contents of the contained object in different elements in the same sequence, excepting vector<bool>, are modified concurrently.
3. [Note: For a vector<int> x with a size greater than one, x[1] = 5 and *x.begin() = 10 can be executed concurrently without a data race, but x[0] = 5 and *x.begin() = 10 executed concurrently may result in a data race. As an exception to the general rule, for a vector<bool> y, y[0] = true may race with y[1] = true. -- end note]

ということで、同一シーケンスコンテナの異なる要素に対しては、データレースを引き起こすことなく別スレッドから安全にアクセス可能。
※ ただし、特殊化されているstd::vector<bool>を除く。毎度々々、不憫な子…