I am trying to convert Java code into Objective C code. And the java code contains variables defined as volatile. I looked online and “volatile” usage in java as follwing
Essentially, volatile is used to indicate that a variable's value will be modified by different threads.
So, If I was going to set variables as volatile in Objective C because the variables are going to be accessed by different threads then I don’t need to set those variables as volatile because I can just set those variables as atomic?
The
volatilekeyword exists in Objective-C as well. You can use it.This is because Objective-C is a superset of C.
Declaring the properties as
atomicwill not correct whatvolatilewas meant to do.volatileeffectively tells the compiler not to optimize away checks done on that variable, because it may have changed when the compiler expected it to stay the same.The simplest example is this. Say we have a global variable declared as:
And it’s later used like this:
We will never get through that loop, because the compiler will say “Hey,
packetsRecievedis never modified in that loop, therefore it will run infinitely.” As a result, it will just make it a straight infinite loop so it can avoid having to check every time.If we instead had declared the variable as:
We are telling the compiler that this variable may change at any time, even when it looks like it should stay the same. So in our example, the machine code generated by the compiler will still have a check on the condition, and our program will work as expected.