patterncppMinor
Win7 atomic access class
Viewed 0 times
classwin7accessatomic
Problem
I have a simple atomic access class designed to work with Windows threads:
Right now I am using it to only atomic-access integers, and the only operators I need are
Testing race conditions is very tricky, so I would like to ask here if my approach will work or if I am missing something.
template
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_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.
Solution
Konrad's answer has a big advantage: it is safe!
In your code sample, if an operator raise an exception before you leave the critical section, this one will never be released. In Konrad's answer, not matter what, the critical section will be unlocked when you exit the scope, even if you don't catch an exception.
In your code sample, if an operator raise an exception before you leave the critical section, this one will never be released. In Konrad's answer, not matter what, the critical section will be unlocked when you exit the scope, even if you don't catch an exception.
Context
StackExchange Code Review Q#12340, answer score: 3
Revisions (0)
No revisions yet.