Is int safe to read from multiple threads?

I have several threads that read the same int variable. and one thread writes the value.

I do not care about the state of the race.

only my concern is that writing and reading an int value is at the same time safe in memory?

and this will not crash the application.

+6
source share
3 answers

Yes, everything should be fine. The only way I can imagine that a failure is if one of the threads releases the memory allocation, which is an integer. For best results, I also need to make sure that the integers are aligned within the limits of sizeof(int) . (Some processors cannot access integers at all without this alignment. Others provide weaker atomicity guarantees for uneven access.)

+4
source

Yes, on x86 and x86-64, as long as the value you are reading is correctly aligned. 32-bit int s, they need to be aligned on a 4-byte border, so that access is atomic when reading, or that will almost always happen if you don't go out of your way to create an unbalanced int (say, using a packed structure or doing custom arithmetic / pointer with byte buffers).

You probably also want to declare your variable as volatile so that the compiler generates code that will repeatedly retrieve the variable from memory each time it is available. This will prevent optimizations such as register caching when it can be modified by another thread.

+2
source

On all Linux platforms that I know of, reading and writing aligned ints is atomic and safe. You will never read a meaning that was not written (without breaking the word). You will never cause an error or failure.

0
source

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


All Articles