简体   繁体   中英

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:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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