Can expression
variable = value; be interrupted "inside"? That is, is it possible during (after the beginning, but before the end) of writing to a variable another entry in the same variable?
In general, the expression
variable = value; can be interrupted "inside". If variable is a variable of a complex type, for example, a struct, then for real assignment, several machine operations will be needed and after each operation a higher priority thread can be inserted. Atomicity can only be spoken for correctly aligned variables no larger than a machine word.
It is necessary to mark a variable as volatile . The variable must be located at the aligned address. (multiple to machine word)
It is necessary that the variable be something that registers in the register: integer, pointer, character.
In any case, it is better to always look at the output to verify this. ( gcc -S )
In C ++, for variables whose type is not std::atomic<T> , during the execution of the expression variable = value writing and reading this variable from other threads is impossible,
because otherwise there would be a data race (data race), and there can be no races in the correct C ++ program (otherwise there will be undefined behavior, UB).
For variables with the type std::atomic<T> entry is atomic by definition of atomicity in C ++.
I think if value is a constant, and variable is declared as volatile , then another thread will not interpose in the middle of this operation.
If access to a variable occurs as a whole (ie, a record, for example, a dvord or fpu state), then the operation is atomic. If the variable is complex, then synchronization is required. Ie in the simplest case, the variable is dvd, and you refer to it as a byte. Hardwarno decides to use the prefix Lock. It makes no sense to programmatically discuss, since this is a problem script.
Source: https://ru.stackoverflow.com/questions/4283/
All Articles