挥发性和缓存行为 [英] Volatile and cache behaviour

查看:119
本文介绍了挥发性和缓存行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看了后结果
 çvolatile变量与高速缓存

不过,我很困惑。

问:结果
      操作系统是否会照顾自己或结果
 程序员在这样一种方式,变量不应该进入缓存提及类似于声明变量作为_Uncached写程序。

Question:
whether OS will take care itself OR
programmer has to write program in such a way that variable should not go into cache as mention like declaring variable as _Uncached.

问候结果
学习

Regards
Learner

推荐答案

要澄清:

挥发性是一个C的概念,告诉编译器从内存中每次取一个变量而不是在寄存器中使用编译器生成的缓存的版本或优化某些$ C $角

volatile is a C concept and tells the compiler to fetch a variable each time from memory rather then use a "compiler-generated" cached version in registers or optimise certain code.

什么可以在这里造成混乱是CPU缓存VS软件缓存(a.k.a在寄存器变量)。

What may be causing confusion here is CPU caches vs software caches (a.k.a variables in registers).

在CPU /硬件缓存是100%透明的程序和硬件可以确保它是100%同步。没有什么可担心那里,当你发出负荷从内存中的数据来自CPU的缓存中,然后它是相同的数据是可寻址的内存。

The CPU/Hardware cache is 100% transparent to the program and the hardware makes sure that it is 100% synchronised. There is nothing to worry there, when you issue a load from memory and the data comes from the CPU cache then it's the same data that is in the addressed memory.

您编译器可能会决定到,虽然缓存经常使用的寄存器,然后可以去不同步内存,因为硬件是不知道这些的变量。这就是挥发性关键字prevents。常见的例子:

Your compiler may decide though to "cache" frequent use variables in registers which can then go out of sync with memory because the hardware is unaware of those. This is what the volatile keyword prevents. Common example:

int * lock;
while (*lock) {
    // do work
    // lock mot modified or accessed here
}

这是优化编译器会看到,你是不是在循环中使用锁定,并将其转换为:

An optimising compiler will see that you are not using lock in the loop and will convert this to:

if (*lock)
    while (true) {
        // do work
    }

这显然不是你想要的行为,如果锁定是由例如修改另一个线程。所以你将其标记为挥发prevent这样的:

This is obviously not the behaviour you want if lock is to be modified by e.g. another thread. SO you mark it volatile to prevent this:

volatile int * lock;
while (*lock) {
    // do work
}

希望这使得它一点点清晰。

Hope this makes it a little clearer.

这篇关于挥发性和缓存行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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