[英]How to protect a non-atomic variable from modification by both interrupt and application code without blocking
我希望能够在不阻塞的情况下修改中断上下文或应用程序上下文中的非原子变量。 为了防止 ISR 阻塞,我使用原子标志来保护非原子数据。
#include <atomic>
#include <cstdint>
using CountLock = std::atomic<bool>;
static_assert(CountLock::is_always_lock_free, "count lock must be lock free");
#define TARGET_COUNT (1000)
CountLock count_locked{false};
uint64_t count{0}; // non-atomic on 32-bit system
// In interrupt
void MyISR()
{
// Don't modify count if locked
if (count_locked)
return;
++count; // non-atomic
if (count == TARGET_COUNT)
// Do something
}
// Application code (not in interrupt)
void setCount(uint64_t newCount)
{
// lock count while we are setting it
count_locked = true;
count = newCount;
count_locked = false;
}
考虑两个线程同时分别调用MyISR
和setCount
:
T1 T2
if (count_locked)
return;
count_locked = true;
++count; /*non-atomic*/ count = newCount; // << data race
if (count == TARGET_COUNT)
// Do something
count_locked = false;
原子不保护对count
写入。
不
数据被修改而没有被正确锁定
是的。 引用何时在多线程中使用 volatile? :“对于平台无关的多线程应用程序编程,易失性(几乎)是无用的。”
不
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.