Write concurrently vector<bool>

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

But the same cannot be said for writing operations. But, I am wondering if this is not always true, for example considering my particular scenario.

I have a std::vector<bool> , where all the elements are initialized to false , and, given an array of indices, I need to change the value of these elements ( vector[index] for each index) from false to true .

If I use a different thread for each index (and there is the possibility that some indices have the same value), can this operation be considered thread-safe?

If the vector is a std::vector<int> (or any primitive type) and the value assigned is always the same (for example 1) can this operation still be considered thread-safe?


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 never lead to data corruption. But as soon as you do any other operation on the same element from two different threads, you will have a race condition and need proper synchronization.


[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> .

链接地址: http://www.djcxy.com/p/76142.html

上一篇: C ++:std :: vector,为两端预留空间

下一篇: 同时写入矢量<bool>