making a class thread safe
-
Hi, I am trying to make my class thread safe with out much luck and wonder if anybody can point me in the right direction. An object of this class is shared between 2 threads, therefore I have added some critical sections but in testing this does not seem to be enough, below is what i have so far:
void CPacket::Lock() { CSingleLock singleLock(&m_CList); singleLock.Lock(); ASSERT(singleLock.IsLocked()); } void CPacket::Unlock() { CSingleLock singleLock(&m_CList); singleLock.Unlock(); ASSERT(!singleLock.IsLocked()); }
and in my code around all use of the object:m_capturedPacket->Lock(); m_capturedPacket->Addpacket() // do something m_capturedPacket->Unlock();
Internally the class mainatins a CList which is being corrupted, how can I make calls to this class thread safe? -
Hi, I am trying to make my class thread safe with out much luck and wonder if anybody can point me in the right direction. An object of this class is shared between 2 threads, therefore I have added some critical sections but in testing this does not seem to be enough, below is what i have so far:
void CPacket::Lock() { CSingleLock singleLock(&m_CList); singleLock.Lock(); ASSERT(singleLock.IsLocked()); } void CPacket::Unlock() { CSingleLock singleLock(&m_CList); singleLock.Unlock(); ASSERT(!singleLock.IsLocked()); }
and in my code around all use of the object:m_capturedPacket->Lock(); m_capturedPacket->Addpacket() // do something m_capturedPacket->Unlock();
Internally the class mainatins a CList which is being corrupted, how can I make calls to this class thread safe?The
CSingleLock
class unlocks the object in its destructor. YourLock()
function locks the critical section, and then when theCSingleLock
object is destroyed when the Lock() function returns, the critical section is unlocked. Try changing your code to this:void CPacket::Lock(){
m_CList.Lock();
ASSERT(m_CList.IsLocked());
}
void CPacket::Unlock(){
m_CList.Unlock();
ASSERT(!m_CList.IsLocked());
}
Software Zen:
delete this;