Overwrites a variable with the same safe value at the same time?

I have the following situation (caused by a defect in the code):

There is a generic variable of a primitive type (let it be int) that is initialized during program startup from exactly one thread to a value N(let it be 0). Then (strictly after the variable is initialized), various threads are launched during program execution, and they randomly read this variable or overwrite it with the same value N( 0in this example). There is no synchronization regarding variable access.

Can this situation cause unexpected behavior in the program?

+3
source share
6 answers

This is incredibly unlikely, but not impossible according to the standard.

Nothing is said about what the basic representation of the integer is, and not the standard indicates how the values ​​are loaded.

I can provide, oddly enough, an implementation where the basic bit pattern for 0 is equal 10101010, and the architecture only supports loading data into memory by shifting bits for eight cycles, but reading it as one element in one cycle.

If another thread reads the offset value at the bit pattern (e.g., 00000001, 00000010, 00000101etc.) have a problem.

, - ​​ , , . , , . , , , , .

, , , , , : -)

+5

++ concurrency, , . , , - . , "" , , "".

++ 0x ( concurrency), undefined. , , concurrency ++ 0x, 1.10, :

, , (Β§1.10/3).

, , , . undefined (Β§1.10/14).

, , , , , undefined.

+3

. , , . , , .

+2

. , (, int ), ( "x = 5;", not "x + = 5;", ).

- , , , - (, ).

+1

, . , 0. 0, .

int , . , 8- (long ) , .

+1

If no other thread (and this does not include the main thread) can change the value 0 to something else (say 1), while these threads are initializing, then you will have no problem. But if any other thread could change the value during the startup phase, you might have a problem. You are playing a dangerous game, and I would recommend blocking it before reading the value.

0
source

Source: https://habr.com/ru/post/1760098/


All Articles