在主程序和C中的ISR之间共享一个volatile变量是否安全? [英] Is it safe to share a volatile variable between the main program and an ISR in C?

查看:84
本文介绍了在主程序和C中的ISR之间共享一个volatile变量是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在主程序和C中的ISR之间使用volatile限定符共享不大于处理器自然字的对齐整数变量安全吗?

Is it safe to share an aligned integer variable, not bigger than the processor natural word, with volatile qualifier, between the main program and an ISR in C? Is it guaranteed that no torn reads or writes may happen?

推荐答案

volatile 关键字并不表示原子性-只是确保明确读取变量且不假定变量未更改。为了在没有任何其他保护机制的情况下进行安全的共享访问,该变量必须同时是原子的并且声明为 volatile

The volatile keyword does not imply atomicity - that simply ensures that a variable is explicitly read and not assumed not to have changed. For safe shared access without any other protection mechanism the variable must be both atomic and declared volatile.

编译器可能对于任何特定目标都是原子性的文档类型,可以为此目的定义 sig_atomic_t

The compiler may document types that are atomic for any particular target, and may define sig_atomic_t for this purpose.

通常假设您的编译器不会做任何错误的事情,并且在指令集允许原子读取的情况下拆分对齐的字读取,可能是合理的。但是,在平台之间移植代码时应谨慎行事-这种低级代码应被视为特定于目标且不可移植。

In general it is perhaps reasonable to assume that your compiler will not do anything perverse and split an aligned word read where the instruction set allows an atomic read. Caution should be applied however when porting code between platforms - such low level code should be regarded as target specific and non-portable.

这篇关于在主程序和C中的ISR之间共享一个volatile变量是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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