I have a Win32 API question about critical sections.
Is it OK to return when in a critical section? Or once you enter the section do you have to fall through and leave the section? Here's some sample code:
//option one
bool doSomething() {
EnterCriticalSection(§ion);
if(something)
return true;
return false;
LeaveCriticalSection(§ion);
}
//option two
bool doSomething() {
bool flag = false;
EnterCriticalSection(§ion);
if(something)
flag = true;
LeaveCriticalSection(§ion);
return flag;
}
I hope I can go with option one and return from inside the section and that will release any locks.
Keep in mind that the Win32 API is written for C. Nothing happens automatically, everything is explicit. So, if you use the API directly, as your example is doing, then you must leave the CS explicitly, otherwise you risk deadlocking other threads that want to enter the CS.
Every successful call to (Try)EnterCriticalSection()
MUST have a corresponding call to LeaveCriticalSection()
. This is stated in the documentation:
A thread uses the EnterCriticalSection or TryEnterCriticalSection function to request ownership of a critical section. It uses the LeaveCriticalSection function to release ownership of a critical section...
... To release its ownership, the thread must call LeaveCriticalSection one time for each time that it entered the critical section...
If you are using a language like C++ that supports OOP programming, and you want to leave the CS automatically when going out of scope, then you need an RAII-style wrapper whose constructor enters the CS and destructor leaves the CS.