对寄存器使用 volatile [英] Use of volatile for registers

查看:67
本文介绍了对寄存器使用 volatile的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道/处理 volatile 声明的效率如何.在以下代码中:

I am wondering how efficient / is working the volatile declaration. In the following code:

volatile char var1 = * (volatile char *) 0x2000000;
printf("%d \n", var1 + 1);

这意味着每次我使用变量var"时,它都会从地址内存0x2000000加载,但是固定地址的易失性转换是必要的,还是只适合var1的类型?

It means that every time I am using the variable "var", it will be loaded from the address memory 0x2000000, but is the volatile cast of a fixed address necessary, or is it only to fit the type of var1?

这是否意味着每次读取var1"时,它都是从内存中读取的,而不是从潜在的缓存值中读取的?那么在这段代码中,我们访问了两次地址 0x2000000?

Does this means that every time "var1" is read, it is read from memory, and not from a potential cached value? So in this code, we access two times the address 0x2000000?

推荐答案

但是固定地址的易失性转换是必要的,(?)

but is the volatile cast of a fixed address necessary, (?)

是的,请考虑以下内容.编译器可以推断 (char *) 0x2000000 被读取一次,volatile char var2 = * (char *) 0x2000000; 不需要再次读取.只需使用之前读取并保存在某些内部存储器/寄存器中的值.目标 var1/var2,是 volatile,不影响赋值的右侧.

Yes, consider the below. Compiler could reason (char *) 0x2000000 was read once, no need to read again for volatile char var2 = * (char *) 0x2000000;. Just use the value that was read before and saved away in some internal memory/register. Targets var1/var2, being volatile, do not affect the right-hand-side of the assignment.

volatile char var1 = * (char *) 0x2000000;
printf("%d \n", var1);
volatile char var2 = * (char *) 0x2000000;
printf("%d \n", var2);

<小时>

不需要带有 volatile char var1volatile.定义一个指向 volatile 数据的指针可能更符合编码目标.


The volatile with volatile char var1 is not needed. Defining a pointer to volatile data is likely more in line with coding goals.

volatile char *ptr1 = (volatile char *) 0x2000000;
printf("%d \n", *ptr1);
printf("%d \n", *ptr1);  // A 2nd read of `(volatile char *) 0x2000000` occurs.

这篇关于对寄存器使用 volatile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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