目标C,将Java中的volatile转换为目标C的最佳方法是什么? [英] Objective C, What is the best way to convert volatile in Java into Objective C?

查看:98
本文介绍了目标C,将Java中的volatile转换为目标C的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Java代码转换为Objective C代码.并且Java代码包含定义为volatile的变量.我将在线和Java中的易失性"用法视为以下原因

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.

因此,如果由于变量将被不同的线程访问而在目标C中将变量设置为volatile,那么我不需要将这些变量设置为volatile,因为我可以将这些变量设置为atomic?

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?

推荐答案

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.

这篇关于目标C,将Java中的volatile转换为目标C的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆