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,NUL L); }
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>::Unloc k()
{
ReleaseMutex(mMutex);
}
template<class T>
void SynchronizedData<T>::SetDa ta(T val)
{
this->Lock();
mData = val;
this->Unlock();
}
template<class T>
T SynchronizedData<T>::GetDa ta()
{
this->Lock();
T retVal = mData;
this->Unlock();
return retVal;
}
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,NUL
T GetData();
void SetData(T val);
void Lock();
void Unlock();
};
template<class T>
inline void SynchronizedData<T>::Lock(
{
WaitForSingleObject(mMutex
mMutex = CreateMutex(NULL,TRUE,NULL
}
template<class T>
inline void SynchronizedData<T>::Unloc
{
ReleaseMutex(mMutex);
}
template<class T>
void SynchronizedData<T>::SetDa
{
this->Lock();
mData = val;
this->Unlock();
}
template<class T>
T SynchronizedData<T>::GetDa
{
this->Lock();
T retVal = mData;
this->Unlock();
return retVal;
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I suspect I will also end up using their thread class in my code as well.
Thanks for the link!
-Sandra