Class member synchronization
hi,
I have following problem:
Example Class A defined as:
class ClassA
{
private:
CRITICAL_SECTION m_mutex;
int var;
public:
ClassA()
{
InitializeCriticalSection(&m_mutex);
var = 0;
}
~ClassA()
{
DeleteCriticalSection(&m_mutex);
}
int GetVar()
{
EnterCriticalSection(&m_mutex);
return var;
LeaveCriticalSection(&m_mutex);
}
void SetVar(int v)
{
EnterCriticalSection(&m_mutex);
var = v;
LeaveCriticalSection(&m_mutex);
}
};
Methods GetVar and SetVar are being called from different threads, of cource.
Problem is that my program hangs up when those methods are being called. So what I need is "class member level" synchronization. Any hints?
See that "warning level" setting on your compiler? Turn it all the way up.
return var;LeaveCriticalSection(&m_mutex);
Quote:Original post by ToohrVykreturn var;LeaveCriticalSection(&m_mutex);
OK, problem solved, thanks, I just didn´t see that :)
In C++ it's better practice to wrap critical section objects in a class type to ensure that all the proper matched calls are actually matched. Ex:
class Mutex { public: Mutex() { InitializeCriticalSection(&cs_); } ~Mutex() { DeleteCriticalSection(&cs_); } private: void lock(void) { EnterCriticalSection(&cs_); } void unlock(void) { LeaveCriticalSection(&cs_); } Mutex(const Mutex &); Mutex & operator=(const Mutex &); CRITICAL_SECTION cs_; friend class Lock;};class Lock { public: explicit Lock(Mutex & m) : m_(m) { m_.lock(); } ~Lock() { m_.unlock(); } private: Lock(const Lock &); Lock & operator=(const Lock &); Mutex & m_;};
Ok, another question:
How to determine when the thread starts waiting on event? Or how to signal event and start waiting simultaneously?
SetEvent(m_hEvent); // Set event signaled
WaitForSingleObject(m_hEvent2, INFINITE); // wait for signaling on another object.
In the code above it takes two method calls to signal and start waiting, but if
there´s multiple threads running, something may happen on other threads between those calls, so I think it isn´t exactly safe.
How to determine when the thread starts waiting on event? Or how to signal event and start waiting simultaneously?
SetEvent(m_hEvent); // Set event signaled
WaitForSingleObject(m_hEvent2, INFINITE); // wait for signaling on another object.
In the code above it takes two method calls to signal and start waiting, but if
there´s multiple threads running, something may happen on other threads between those calls, so I think it isn´t exactly safe.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement