Sign in to follow this  
murjara

Class member synchronization

Recommended Posts

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?

Share this post


Link to post
Share on other sites
See that "warning level" setting on your compiler? Turn it all the way up.

return var;
LeaveCriticalSection(&m_mutex);



Share this post


Link to post
Share on other sites
Quote:
Original post by ToohrVyk

return var;
LeaveCriticalSection(&m_mutex);



OK, problem solved, thanks, I just didn´t see that :)

Share this post


Link to post
Share on other sites
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_;
};

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this