I have these two methods for thread-exclusive access to a CMyBuffer
object:
Header:
class CSomeClass
{
//...
public:
CMyBuffer & LockBuffer();
void ReleaseBuffer();
private:
CMyBuffer m_buffer;
CCriticalSection m_bufferLock;
//...
}
Implementation:
CMyBuffer & CSomeClass::LockBuffer()
{
m_bufferLock.Lock();
return m_buffer;
}
void CSomeClass::ReleaseBuffer()
{
m_bufferLock.Unlock();
}
Usage:
void someFunction(CSomeClass & sc)
{
CMyBuffer & buffer = sc.LockBuffer();
// access buffer
sc.ReleaseBuffer();
}
- What I like about this is, that the user has to make only one function call and can only access the buffer after having locked it.
- What I don't like is that the user has to release explicitly.
Update: These additional disadvantages were pointed out by Nick Meyer and Martin York:
- The user is able to release the lock and then use the buffer.
- If an exception occurs before releasing the lock, the buffer remains locked.
I'd like to do it with a CSingleLock
object (or something similar), which unlocks the buffer when the object goes out of scope.
How could that be done?