易失的变量,只能在ISR中读取? [英] volatile for variable that is only read in ISR?

查看:127
本文介绍了易失的变量,只能在ISR中读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在主循环中读写的变量是否需要volatile,但在ISR中为只读变量?

Is volatile needed for a variable that is read&write in main loop, but read-only in ISR?

在写main时,ISR被禁用.因此,该变量可有效地原子使用.

At the moment of writing in main, the ISR is disabled. So, the variable is effectively used atomically.

(非常相关):

用于中断的易失性与内存屏障

推荐答案

volatile是同步访问的错误方法.这是一个优化障碍,但不是更多.

volatile is a bad way to synchronize access. It is an optimization barrier but not more.

  • 它不是原子的;例如在没有本机64位数据类型的平台上,当some_typeuint64_t时,可能只读取了一部分.例如

  • it is not atomic; e.g. when your some_type is uint64_t on a platform without native 64 bit datatypes, there might be read only a part. E.g.

main()                  irq()

/* initialization */ 
var[0..31]  = 4
var[32..63] = 8

/* modificatoin */ 
var[32..63] = 23
                      /* read */
                      a_hi = var[32..64] = 32
                      a_lo = var[0..31]  = 4
var[0..31] = 42

  • 取决于体系结构,可能需要进行内存屏障操作.例如.当mainirq在具有专用缓存的不同内核上运行时,irq将永远看不到更新后的值

  • depending on architecture, there might be needed memory barrier operations. E.g. when main and irq runs on different cores which have dedicated caches, the irq will never see the updated value

    第一个问题需要锁定,但是锁定操作通常意味着优化障碍,因此volatile是多余的.

    The first problem requires locking but locking operations usually imply an optimization barrier, so that volatile is superfluously.

    同上解决第二个问题,即内存屏障也充当优化屏障.

    Ditto for the second problem where memory barriers act as an optimization barrier too.

    volatile对于实现对处理器内存的访问很有用(在两次读取之间可能会更改,或者在写入时会产生副作用).但是通常,它是不需要的并且太昂贵了.

    volatile is useful for implementing access to processor memory (which might change between two reads or have side effects when writing). But usually, it is unneeded and too expensive.

    这篇关于易失的变量,只能在ISR中读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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