











volatile 是 C/C++ 中的一个类型修饰符,用于告诉编译器该变量可能会被程序之外的因素(如硬件、操作系统、其他线程)改变,因此编译器不应该对该变量进行优化。
volatile 变量进行寄存器缓存优化// 硬件寄存器映射
volatile uint32_t *uart_status = (volatile uint32_t*)0x4000_0000;
// 等待硬件状态改变
while ((*uart_status & 0x01) == 0) {
// 等待数据就绪
}
volatile bool interrupt_flag = false;
// 中断服务程序
void ISR() {
interrupt_flag = true;
}
// 主程序
int main() {
while (!interrupt_flag) {
// 等待中断
}
// 处理中断事件
}
volatile bool thread_should_stop = false;
// 工作线程
void worker_thread() {
while (!thread_should_stop) {
// 执行任务
}
}
// 主线程
void stop_worker() {
thread_should_stop = true;
}
// ADC 转换结果
volatile uint16_t adc_result;
// DMA 传输完成标志
volatile bool dma_complete = false;
// 定时器计数器
volatile uint32_t timer_counter;
volatile 不能保证原子性// 错误用法 - 非线程安全
volatile int counter = 0;
counter++; // 不是原子操作
// 正确用法 - 使用原子操作
#include <atomic>
std::atomic<int> counter(0);
counter++; // 原子操作
// 指向 volatile 数据的指针
volatile int *ptr;
// volatile 指针指向 const 数据
int *volatile const_ptr;
// const volatile - 不能被程序修改但可能被外部改变
const volatile uint32_t *hardware_register;
// 错误观念
volatile bool flag = false;
// 线程1
flag = true;
// 线程2
if (flag) {
// 不能保证看到最新值
}
volatile int a = 0;
volatile int b = 0;
// 线程1
a = 1;
b = 2;
// 线程2可能看到 b=2 时 a 仍然是 0
#include <atomic>
std::atomic<bool> flag{false};
std::atomic<int> counter{0};
// 原子操作
counter.fetch_add(1);
flag.store(true);
bool value = flag.load();
#include <mutex>
std::mutex mtx;
int shared_data = 0;
void safe_increment() {
std::lock_guard<std::mutex> lock(mtx);
shared_data++;
}
| 场景 | 是否使用 volatile | 推荐方案 |
|---|---|---|
| 硬件寄存器访问 | ✅ | volatile |
| 中断标志位 | ✅ | volatile |
| 多线程共享变量 | ❌ | std::atomic |
| 需要原子操作 | ❌ | std::atomic |
| 需要互斥访问 | ❌ | std::mutex |
// 嵌入式开发
volatile uint32_t * const UART_REG = (volatile uint32_t*)0x4000_0000;
// 中断处理
static volatile bool irq_pending = false;
// 现代 C++ 多线程
std::atomic<bool> stop_flag{false}; // 替代 volatile
************************************************************************************************
作者:huakaimanlin
出处:https://www.cnblogs.com/huakaimanlin/
版权所有,如需转载请声明出处
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。