我目前正在使用 Atmel AVR 微控制器 (gcc),但希望答案适用于一般的微控制器世界,即通常是单线程但带有中断。
volatile
我知道在访问可以在 ISR 中修改的变量时如何在 C 代码中使用。例如:
uint8_t g_pushIndex = 0;
volatile uint8_t g_popIndex = 0;
uint8_t g_values[QUEUE_SIZE];
void waitForEmptyQueue()
{
bool isQueueEmpty = false;
while (!isQueueEmpty)
{
// Disable interrupts to ensure atomic access.
cli();
isQueueEmpty = (g_pushIndex == g_popIndex);
sei();
}
}
ISR(USART_UDRE_vect) // some interrupt routine
{
// Interrupts are disabled here.
if (g_pushIndex == g_popIndex)
{
usart::stopTransfer();
}
else
{
uint8_t value = g_values[g_popIndex++];
g_popIndex &= MASK;
usart::transmit(value);
}
}
因为 g_popIndex 在 ISR 内部修改并在 ISR 外部访问,所以必须声明它volatile
以指示编译器不要优化对该变量的内存访问。请注意,除非我弄错了,g_pushIndex
并且g_values
不需要声明volatile
,因为它们没有被 ISR 修改。
我想把队列相关的代码封装在一个类里面,这样就可以复用了:
class Queue
{
public:
Queue()
: m_pushIndex(0)
, m_popIndex(0)
{
}
inline bool isEmpty() const
{
return (m_pushIndex == m_popIndex);
}
inline uint8_t pop()
{
uint8_t value = m_values[m_popIndex++];
m_popIndex &= MASK;
return value;
}
// other useful functions here...
private:
uint8_t m_pushIndex;
uint8_t m_popIndex;
uint8_t m_values[QUEUE_SIZE];
};
Queue g_queue;
void waitForEmptyQueue()
{
bool isQueueEmpty = false;
while (!isQueueEmpty)
{
// Disable interrupts to ensure atomic access.
cli();
isQueueEmpty = g_queue.isEmpty();
sei();
}
}
ISR(USART_UDRE_vect) // some interrupt routine
{
// Interrupts are disabled here.
if (g_queue.isEmpty())
{
usart::stopTransfer();
}
else
{
usart::transmit(g_queue.pop());
}
}
上面的代码可以说更具可读性。volatile
但是,在这种情况下应该怎么做呢?
1)还需要吗?即使声明了函数,调用该方法是否Queue::isEmpty()
以某种方式确保对 的非优化访问?我不信。我知道编译器使用启发式方法来确定是否不应该优化访问,但我不喜欢依赖这种启发式方法作为通用解决方案。g_queue.m_popIndex
inline
2)我认为一个有效(有效)的解决方案是Queue::m_popIndex
volatile
在类定义中声明成员。但是,我不喜欢这种解决方案,因为类的设计者Queue
需要确切知道如何使用它来知道必须是哪个成员变量volatile
。它不会随着未来的代码更改而很好地扩展。此外,所有Queue
实例现在都将拥有一个volatile
成员,即使有些实例未在 ISR 中使用。
3) 如果将Queue
类视为内置类,我认为自然的解决方案是将全局实例g_queue
本身声明为volatile
,因为它在 ISR 中被修改并在 ISR 之外访问。但是,这并不好用,因为只能volatile
对volatile
对象调用函数。Queue
突然之间,必须声明的所有成员函数volatile
(不仅仅是const
ISR 中使用的那些或那些)。再说了,设计者怎么能Queue
提前知道呢?此外,这会惩罚所有Queue
用户。仍然存在复制所有成员函数并在类中同时具有volatile
和非volatile
重载的可能性,因此非volatile
用户不会受到惩罚。不漂亮。
4)Queue
该类可以在策略类上进行模板化,该策略类可以选择性地volatile
仅在需要时添加到其所有成员变量。同样,类设计者需要提前知道这一点,解决方案更难理解,但是哦,好吧。
我很想知道我是否缺少一些更简单的解决方案。作为旁注,我正在编译没有 C++11/14 支持(还)。