Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to access (read) a bit from a bitset (C++) which may be modified by a different thread

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);
// ...
like image 598
Eugene Spruntberger Avatar asked Oct 29 '22 01:10

Eugene Spruntberger


1 Answers

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.

like image 137
LWimsey Avatar answered Nov 15 '22 05:11

LWimsey