المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Data integrity question.



C++ Programming
07-26-2009, 04:02 AM
I have a reader that reads an int
and I have a writer that modifies that int.

In other words I have an int called iVal :
int iVal;

And I have a thread A that constantly reads iVal and another different thread B that, sometimes modifies the value of iVal.

My concern is with problems that may arise when A is reading iVal at the same time B is modifying it.

I used to rely on InterlockedIncrement,etc whenever I have the scenario of two writers for the same variable.

But what if my writer (B) could do more than a simple incrementation and that my readers must read the value as it is just before the writer could modify it or as it is just after it would be modified ?

I'm not sure already that the depicted scenario is unsafe. It data incorrectness could happen and cause the reader to behave in unplanned way. Moreover I seek a simple way without introducing a critical section for iVal variable :

Ie I want to avoid having to wrap the simple iVal into a class and do things like the following :


Class CValue{
private :
CCRITICAL_SECTION cs;
int iVal;
public:
CValue()
{
InitializeCriticalSection(&cs);
}
~CValue()
{
DeleteCriticalSection(&cs);
}
void setValue(int iVal)
{
EnterCriticalSection(&cs);
this->iVal = iVal;
LeaveCriticalSection(&cs);
}
int getValue()
{
int _iVal;
EnterCriticalSection(&cs);
_iVal = iVal;
LeaveCriticalSection(&cs);
return _iVal;
}
}


Thank you..in advance.

Easy Profiler : a compile-time profiler for C++
www.potatosoftware.com