易失的变量,只能在ISR中读取? [英] volatile for variable that is only read in 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_type
是uint64_t
时,可能只读取了一部分.例如
it is not atomic; e.g. when your
some_type
isuint64_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
取决于体系结构,可能需要进行内存屏障操作.例如.当main
和irq
在具有专用缓存的不同内核上运行时,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屋!