I have multiple threads reading same int variable. and one thread is writing the value.
I don't care about the race condition.
only my concern is writing and reading int value at same time is memory safe ?
and it will not result in any application crash .
Yes, that should be all right. The only way I can envision that crashing is if one of the threads deallocates the memory backing that integer. For best results I would also make sure the integers are aligned at sizeof(int)
boundaries. (Some CPUs cannot access integers at all without this alignment. Others provide weaker guarantees of atomicity for unaligned access.)
Yes, on x86 and x86-64, as long as the value you're reading is aligned properly. 32-bit int
s, they need to be aligned on a 4-byte boundary in order for access to be atomic when reading or writing, which will almost always be the case unless you go out of your way to create unaligned int
s (say, by using a packed structure or by doing casting/pointer arithmetic with byte buffers).
You probably also want to declare your variable as volatile
so that the compiler will generate code that will re-fetch the variable from memory every time it's accessed. That will prevent it from making optimizations such as caching it in a register when it might be altered by another thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With