前提:我正在使用甚至没有C ++ 11(带有std::atomic<int>)的ARM嵌入式(几乎是裸机)环境,因此请避免回答“ 仅使用标准C ++std::atomic<int> ”之类的答案:我不能。
这个AtomicInt的ARM 实现正确吗?(假设ARM体系结构是ARMv7-A)
您看到一些同步问题吗?是否volatile需要/有用?
// File: atomic_int.h
#ifndef ATOMIC_INT_H_
#define ATOMIC_INT_H_
#include <stdint.h>
class AtomicInt
{
public:
AtomicInt(int32_t init = 0) : atom(init) { }
~AtomicInt() {}
int32_t add(int32_t value); // Implement 'add' method in platform-specific file
int32_t sub(int32_t value) { return add(-value); }
int32_t inc(void) { return add(1); }
int32_t dec(void) { return add(-1); }
private:
volatile int32_t atom;
};
#endif
Run Code Online (Sandbox Code Playgroud)
// File: arm/atomic_int.cpp …Run Code Online (Sandbox Code Playgroud)