multithreading - 这里需要 volatile 吗?

标签 multithreading gcc locking c99 volatile

我有一个功能,可以更新结构,并禁用中断。

bool readBuffer()
{
    __disable_irq();

    rb->reader += 1; // Just an example

    __enable_irq();

    return true;
}

因为中断被禁用,所以在更新结构中的值时不可能有另一个中断抢占。

但我是否也应该将读者变量标记为 volatile ?因为理论上另一个中断可以在我进入函数时抢占,但就在 __disable_irq() 之前实际上被称为。当我的函数恢复时,缓存值 rb->reader将是不正确的。或者编译器 (GCC) 生成的代码不缓存 rb->reader直到那条线真正被击中?

最佳答案

指定显式优化障碍可能会更好:

bool readBuffer()
{
    __disable_irq();
    asm volatile ("" ::: "memory"); // Some unexpected memory modification
    rb->reader += 1; // Just an example
    __enable_irq();
    return true;
}

如果在某些其他情况下您希望编译器优化 rb->reader,这将是有利可图的。变量,因此将其标记为 volatile 将是多余的。

关于multithreading - 这里需要 volatile 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14441692/

相关文章:

java - 线程同步问题(更新变量 sum)

java - 死锁和同步方法

c++ - 当尝试用 C++ 编写代码时,我收到一长串错误,例如 "/tmp/ccloHU4h.o:dad.cpp:(.text+0x5c): undefined reference to ` std::cout'"

c# - Task.Factory.StartNew() 是否保证使用调用线程之外的另一个线程?

python - Django - 如何处理并发?

c# - 让后台 worker 保持活力

linux - POSIX 线程是用户级别的吗?

C: 宏产生警告 "statement with no effect"

ios - 结构填充编译标志

Mongodb findAndModify原子性