更新时间:2023-01-22 22:43:23
Objective-C中也存在volatile
关键字.您可以使用它.
The volatile
keyword exists in Objective-C as well. You can use it.
这是因为Objective-C是C的超集.
This is because Objective-C is a superset of C.
将属性声明为atomic
不会纠正volatile
的含义. volatile
有效地告诉编译器不要优化对该变量执行的离开检查,因为当编译器期望它保持不变时,它可能已更改.
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;
后来被这样使用:
packetsRecieved = 0;
while (packetsRecieved < 10){
//Wait for more packets
}
processPackets();
我们将永远不会通过该循环,因为编译器会说:嘿,packetsRecieved
从未在该循环中被修改,因此它将无限运行."结果,它只会使其成为一个直线无限循环,从而避免了每次都要检查的情况.
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.