struct ExecutionLock
{
ExecutionLock(CRITICAL_SECTION* _lock)
{
lock = _lock;
EnterCriticalSection(lock);
}
~ExecutionLock()
{
LeaveCriticalSection(lock);
}
CRITICAL_SECTION lock;
}
void SampleClass::sampleFunction()
{
ExecutionLock lockFunc(lock_);
// Code which I want to be executed by a single thread at one time
}
My question is, Is this a valid method to be using? Would I take a big hit on performance if the functions gets slightly larger? Would I face other consequences from using such method in my functions?
Yes, that's a very common usage of RAII, and is in fact the preferred method to deal with mutexes in C++. The generated code is equivalent to what you'd get if you wrote the locks and unlocks yourself, but it has the advantage that the compiler will not forget to unlock the mutex, even if you return early or throw an exception.