Link to home
Start Free TrialLog in
Avatar of Sandra-24
Sandra-24

asked on

Threadsafe code

I got tired of constantly making mutexes and having to manually wait for them and release them and create them.

So I thought good time for an OO solution and set about to build a SynchronizedData template class that will keep any type of object from being accessed simultaneously.

I think the basic design is right, but I'm not sure I did the Lock() or Unlock() method correctly. Does it look good to you?

template<class T>
class SynchronizedData
{
private:
      T mData;
      HANDLE mMutex;

public:
      SynchronizedData() { mMutex = CreateMutex(NULL,FALSE,NULL); }

      T GetData();
      void SetData(T val);

      void Lock();
      void Unlock();
};

template<class T>
inline void SynchronizedData<T>::Lock()
{
      WaitForSingleObject(mMutex,INFINITE); //wait for object and then lock it
      mMutex = CreateMutex(NULL,TRUE,NULL); //locked
}

template<class T>
inline void SynchronizedData<T>::Unlock()
{
      ReleaseMutex(mMutex);
}

template<class T>
void SynchronizedData<T>::SetData(T val)
{
      this->Lock();
      mData = val;
      this->Unlock();
}

template<class T>
T SynchronizedData<T>::GetData()
{
      this->Lock();
      T retVal = mData;
      this->Unlock();
      return retVal;
}
ASKER CERTIFIED SOLUTION
Avatar of YuriPutivsky
YuriPutivsky

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Sandra-24
Sandra-24

ASKER

Excellent classes. I borrowed the whole lot for my code:)

I suspect I will also end up using their thread class in my code as well.

Thanks for the link!

-Sandra