简体   繁体   English

在这些条件下设置可变原子

[英]Is Setting a Variable Atomic in THESE conditions

I have this situation where I have a state variable; 在这种情况下,我有一个状态变量。 int state = (2, 1, 0) and an infinite loop: int state =(2,1,0)和一个无限循环:

ret = BoolCompareAndSwap(state, 1, 2)
if (ret) {
    // Change something ...
    state = 0;
}

Would this state setting be atomic? 这个状态设置是原子的吗? Assuming to set a variable you must: 假设设置变量,您必须:

  1. Take out from memory 从内存中取出
  2. Change value 变更价值
  3. Set new value 设定新值

If some other thread came and compared the variable, it would be atomic since the actual value doesn't change until it it re-set in memory, Correct? 如果有其他线程来比较该变量,那么它将是原子的,因为直到将其重新设置在内存中,实际值才会改变,对吗?

Strictly speaking, C compilers would still be standard conforming if they wrote the state bitwise. 严格来说,如果C编译器按位编写状态,则它们仍然符合标准。 After writing the first few bits, some other thread can read any kind of garbage. 写入前几位后,其他一些线程可以读取任何类型的垃圾。
Most compilers do no such thing (with the possible exception of compilers for ancient 4bit processors or even narrower ...), because it would be a performance loss. 大多数编译器都不做这种事情(可能是较旧的4位处理器甚至更窄的编译器除外……),因为这会降低性能。

Also, and more practically relevant, if any other thread writes (instead of only reading) to the state, that written value can get lost if you do not protect the described code against racing conditions. 而且,在实际中更相关的是,如果有任何其他线程向状态写入(而不是仅读取),则如果您不保护所描述的代码不受竞争条件的影响,则该写入的值可能会丢失。

As a side note, the described state change (read, modify, write) is never atomic. 附带说明,所描述的状态更改(读取,修改,写入)绝不是原子的。 The question however when that non-atomicity is vulnerable, is valid and it is what I tried to answer above. 但是,当这种非原子性很脆弱时,这个问题是正确的,这就是我上面试图回答的问题。

More generically speaking, thinking through all possible combinations of concurrent access is a valid protection mechanism. 更笼统地说,考虑并发访问的所有可能组合是一种有效的保护机制。 It is however extremely costly in many ways (design effort, test effort, risk during maintenance...). 但是,它在许多方面都非常昂贵(设计工作,测试工作,维护期间的风险...)。
Only if those costs are in total smaller than the intended saving (possibly performance), it is feasible to go that way, instead of using an appropriate protection mechanism. 仅当这些成本总计小于预期的节省(可能是性能)时,才可以这样做,而不是使用适当的保护机制。

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

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