I have a simple atomic access class designed to work with Windows threads:
template <class aa_type>
class AtomicAccess{
private:
CRITICAL_SECTION lock;
aa_type value;
public:
AtomicAccess(){
InitializeCriticalSection(&lock);
}
~AtomicAccess(){
DeleteCriticalSection(&lock);
}
AtomicAccess &operator=(const aa_type &val){
EnterCriticalSection(&lock);
value = val;
LeaveCriticalSection(&lock);
return *this;
}
AtomicAccess &operator++(int){
EnterCriticalSection(&lock);
value++;
LeaveCriticalSection(&lock);
return *this;
}
AtomicAccess &operator--(int){
EnterCriticalSection(&lock);
value--;
LeaveCriticalSection(&lock);
return *this;
}
bool operator==(const aa_type &val){
aa_type current;
EnterCriticalSection(&lock);
current = value;
LeaveCriticalSection(&lock);
return current == val;
}
bool operator!=(const aa_type &val){
aa_type current;
EnterCriticalSection(&lock);
current = value;
LeaveCriticalSection(&lock);
return current != val;
}
};
typedef AtomicAccess<int> int_aa;
Right now I am using it to only atomic-access integers, and the only operators I need are =
(for assignment), ++
, --
, ==
and !=
. If I decide I need more operators, I will add them.
Testing race conditions is very tricky, so I would like to ask here if my approach will work or if I am missing something.