Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is int safe to read from multiple threads?

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 .

like image 268
Vivek Goel Avatar asked Sep 28 '11 17:09

Vivek Goel


2 Answers

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

like image 200
asveikau Avatar answered Oct 31 '22 00:10

asveikau


Yes, on x86 and x86-64, as long as the value you're reading is aligned properly. 32-bit ints, 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 ints (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.

like image 39
Adam Rosenfield Avatar answered Oct 30 '22 22:10

Adam Rosenfield