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 volatile keyword can be used either with primitive type or objects. The volatile keyword does not cache the value of the variable and always read the variable from the main memory. The volatile keyword cannot be used with classes or methods.
The volatile modifier is used to let the JVM know that a thread accessing the variable must always merge its own private copy of the variable with the master copy in the memory. Accessing a volatile variable synchronizes all the cached copied of the variables in the main memory.
The volatile keyword is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler. Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time.
The volatile
keyword exists in Objective-C as well. You can use it.
This is because Objective-C is a superset of C.
Declaring the properties as atomic
will not correct what volatile
was meant to do. volatile
effectively 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:
int packetsReceived = 0;
And it's later used like this:
packetsRecieved = 0;
while (packetsRecieved < 10){
//Wait for more packets
}
processPackets();
We will never get through that loop, because the compiler will say "Hey, packetsRecieved
is 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:
volatile int packetsRecieved;
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.
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