Is this type of operation considered safe? (in other words no chance of reading some bogus intermediate value if the bitset is being modified on a different thread)? Specifically I'm only interested in whether the read is safe, in other words, I am not asking whether it's safe to write to a bitset from two separate threads.
eg: Will thread 1 reliably get the current state of bit 5 regardless of whether other bits in bs are being set/cleared at the same time?
std::bitset<64> bs;
//thread 1:
bool val;
val=bs.test(5);
// ...
//thread 2:
// set/clear a few bits
bs.set(1);
bs.set(3);
bs.set(5);
bs.reset(6);
// ...
Using a std::bitset
that way is not thread safe.
This is what the standard says about accessing a bitset (§ 20.9.2.2-51):
For the purpose of determining the presence of a data race, any access or update through the resulting reference potentially accesses or modifies, respectively, the entire underlying bitset.
Therefore, writing to a bitset object while reading from it in another thread of execution is a data race (which triggers undefined behavior). Even if all threads access the bitset object using a different index.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With