I'm interested in general concept not in specific solution.
If we have type casting like this:
int x;
float y;
y = (float) x;
Disasm:
main:
push rbp
mov rbp, rsp
pxor xmm0, xmm0
cvtsi2ss xmm0, DWORD PTR [rbp-4]
movss DWORD PTR [rbp-8], xmm0
nop
pop rbp
ret
Is type casting operation itself is atomic?
Can it be somehow preempted?
Cant we get an undefined behaviour if in time of casting another process/thread changed half of the bytes in x?
Atomicity is about accessing objects in memory.
Converting between types is an operation on values, not on objects. Therefore, converting has no relationship to atomicity.
Your question seems to presume that
y = (float) x;might be some sort of single operation that converts anintvalue stored inxto afloatvalue iny. However, this is not the case. Iny = (float) x);, there are three operations:xis loaded:xis an lvalue that designates an object in memory. Per C 2018 6.3.2.1 2, this lvalue is converted to the value stored inx. In other words, the value ofxis loaded from memory. (Ifxwere atomic, it would be an atomic load.) The result of this operation is merely a value, not an object. In particular, it is not atomic, even ifxwas atomic; C 2018 6.3.2.1 2 says “… if the lvalue has atomic type, the value has the non-atomic version of the type of the lvalue…”(float)is a cast operator that says to convert the value tofloat. This conversion is performed using the value, not any object. The result is afloatvalue.y:y =says to store the value iny. (Ifywere atomic, it would be an atomic store.)Since
xis not atomic, if some other thread changesxin the middle of it being loaded, the load operation could get a bad value forx.This does not affect the conversion to
float; that is a separate operation.