0
AtomicPointer在性LevelDB實現如下:hava我對AtomicPointer有錯誤的理解?
class AtomicPointer {
private:
void* rep_;
public:
AtomicPointer() { }
explicit AtomicPointer(void* p) : rep_(p) {}
inline void* NoBarrier_Load() const { return rep_; }
inline void NoBarrier_Store(void* v) { rep_ = v; }
inline void* Acquire_Load() const {
void* result = rep_;
MemoryBarrier();
return result;
}
inline void Release_Store(void* v) {
MemoryBarrier();
rep_ = v;
}
};
現在,我想要做一些測試,我的目標是驗證AtomicPointer的原子性,這裏是步驟: 1.初始化一個結構包含整數 2 。一個線程將整數加1,而另一個線程檢查整數是否相等,如果不相等,則報告錯誤。
//thread0 callback
unsigned __stdcall apLoad(void * d)
{
MemoryBarrier();
while (true)
{
B* pb = (B*)ap.Acquire_Load();// B is a struct contains Integer a,b,c
pb->a ++;
pb->b ++;
pb->C++;
ap.Release_Store((void*)pb);
}
}
//thread1 callback
unsigned __stdcall apStore(void * d)
{
while (true)
{
B* pb = (B*)ap.Acquire_Load();
if(!(pb->a == pb->b && pb->b == pb->c))
{
printf("error : %d-%d-%d\r\n",pb->a,pb->b,pb->c);
}
}
}
//here is the definition of B
typedef struct
{
int a;
int b;
int c;
} B;
我的問題是,在thread1,它是如何發生的,它會打印出「錯誤」!