Locking a code block with an object

I do have couple of functions which I want to be executed by a single thread at one time.
I could think of a solution as such:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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?
Last edited on
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.
Topic archived. No new replies allowed.