简体   繁体   English

从bitset(C ++)访问(读取)位是否安全,可以由不同的线程修改

[英]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)? (换句话说,如果在不同的线程上修改了bitset,则没有机会读取一些虚假的中间值)? 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. 具体来说,我只对读取是否安全感兴趣,换句话说,我不会问从两个独立的线程写入一个bitset是否安全。

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? 例如:无论是否同时设置/清除bs中的其他位,线程1是否可靠地获得第5位的当前状态?

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);
// ...

Bitset does not offer atomic modification, so changes of bits may latch older values in nearby bits. Bitset不提供原子修改,因此位的更改可能会锁定附近位中的较旧值。

If there was a reset(5) that may mean thread 1 never sees the set bit. 如果存在重置(5),则可能意味着线程1从未看到设置位。

Using a std::bitset that way is not thread safe. 以这种方式使用std::bitset 不是线程安全的。

This is what the standard says about accessing a bitset (§ 20.9.2.2-51): 这是标准关于访问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). 因此,在另一个执行线程中从其读取时写入bitset对象是数据争用(触发未定义的行为)。 Even if all threads access the bitset object using a different index. 即使所有线程都使用不同的索引访问bitset对象。

No STL container is thread-safe. 没有STL容器是线程安全的。 While you will not get an intermediate value, you might end up ignoring a set of the value if the threads are not synchronized. 虽然您不会获得中间值,但如果线程未同步,您最终可能会忽略一组值。 Use atomic operations. 使用atomic操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM