gpt4 book ai didi

c++ - volatile 成员变量与 volatile 对象?

转载 作者:行者123 更新时间:2023-12-02 10:21:01 32 4
gpt4 key购买 nike

我正在尝试在下面的“MpscQueue.h”中的嵌入式目标上实现多个生产者(通过中断)、单个消​​费者(通过应用程序线程)队列。

我想知道我是否可以安全地删除一些 volatile下面的用法(见内联问题)。我也会考虑使用 volatile std::array代替 C 风格 buffer_[]如下所示,但我不确定我是否可以相信它的实现与下面的意图相匹配。第三种选择是将 MpscQueue 对象本身标记为 volatile并对相关方法进行限定volatile ,但尚不清楚这是否会导致所有成员变量(以及它们指向的,在指针的情况下)被视为 volatile 。

对此有何指导?

template<typename T, uint32_t depth>
class MpscQueue
{
public:
MpscQueue(void);
bool push(T& t);
bool pop(T* const t);

private:
T volatile buffer_[depth]; // Q1: is volatile unnecessary if never access buffer_[]?
T volatile* const begin_; // Q2: is volatile unnecessary if never access value
T volatile* const end_; // via begin_/end_?
T volatile* head_; // volatile required so that thread always checks value
T volatile* volatile tail_; // Q3: is 'T volatile' required so that ISR accounts
// for other ISRs when setting value?
// Q4: is '* volatile' required so that ISR accounts
// for other ISRs when checking pointer?
};

template<typename T, uint32_t depth>
MpscQueue<T, depth>::MpscQueue(void) :
begin_(&buffer_[0]),
end_(&buffer_[depth - 1]),
head_(begin_),
tail_(begin_)
{}

template<typename T, uint32_t depth>
bool MpscQueue<T, depth>::push(T& t)
{
// "Multiple producer" ISRs can use this function to push at tail

// Pseudo-code: if not full, *(tail_++) = t
}

template<typename T, uint32_t depth>
bool MpscQueue<T, depth>::pop(T* const t)
{
// "Single consumer" thread can use this function to pop at head

// Pseudo-code: if not empty, *t = *(head_++)
}

编辑:为了将问题集中在正确的方向,让我澄清一下我已经处理了线程安全,这不是这里问题的一部分。

因为这个队列是单一消费者,所以在读/弹出端不需要线程安全。在写入/推送方面,中断之间的线程安全将通过将所有相关中断设置为相同的优先级来处理(否则将使用锁)。

最佳答案

正如所写的那样,代码不是中断安全的——如果在主线程执行读取/弹出时发生中断,则您有竞争条件,并且数据结构可能已损坏。解决此问题的方法是在主线程执行读取/弹出操作时阻止中断。如果您这样做(并且阻止/取消阻止中断的功能是内存屏障),那么 volatile 都变得无关紧要并且可以被删除。

Volatile 对于线程同步几乎没用——它的主要用途是与内存映射设备进行交互。

关于c++ - volatile 成员变量与 volatile 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60139241/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com