Write concurrently vector

后端 未结 2 687
时光说笑
时光说笑 2020-11-29 11:32

I know that is possible to read concurrently from a std::vector without \"bad\" consequences because this operation can be considered thread-safe.

But t

相关标签:
2条回答
  • 2020-11-29 11:52

    [container.requirements.dataraces]/2 says:

    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 container, excepting vector<bool>, are modified concurrently.

    So you can safely modify distinct elements of the same standard library container from distinct threads, except when that container is vector<bool>.

    0 讨论(0)
  • 2020-11-29 12:06

    Concurrent writes to vector<bool> are never ok, because the underlying implementation relies on a proxy object of type vector<bool>::reference which acts as if it was a reference to bool, but in reality will fetch and update the bitfield bytes as needed.

    When using multiple threads without synchronization, the following might happen: Thread 1 is supposed to update a bit, and reads the byte containing it. Then thread 2 reads the same byte, then thread 1 updates a bit and writes the byte back, and then thread 2 updates another bit and writes the byte back, overwriting the edit of thread 1.

    This is just one possible scenario, there are others that would lead to the same kind of data corruption.


    In the vector<int> situation, if you are absolutely sure that all threads write the same value into the vector, then this operation will generally not lead to data corruption. However, the standard is of course always extra careful and defines all concurrent accesses to a memory location, of which at least one is a write access, to be undefined behavior:

    Two expression evaluations conflict if one of them modifies a memory location and the other one reads or modifies the same memory location. – intro.races/2

    Therefore, as soon as you do any modification operation on the same element from two different threads, you will have a race condition and need proper synchronization, e.g. by using std::atomic<int>.

    0 讨论(0)
提交回复
热议问题