You can create a class LockCriticalSection, which lock a critical section in the constructor and unlock the critical section in the destructor.
Then, in your code you allocate a LockCriticalSection object where you want to start the lock. The critical section will be released automatically when the object LockCriticalSection goes out of scope (because the function terminates correctly or because of an exception)
The following is the code that takes care of locking and unlocking the critical section:
/// \brief This class locks a critical section in the
/// constructor and unlocks it in the destructor.
///
/// This helps to correctly release a critical section in
/// case of exceptions or premature exit from a function
/// that uses the critical section.
///
///////////////////////////////////////////////////////////
class LockCriticalSection
{
public:
/// \brief Creates the object LockCriticalSection and
/// lock the specified CRITICAL_SECTION.
///
/// @param pCriticalSection pointer to the CRITICAL_SECTION
/// to lock
///
///////////////////////////////////////////////////////////
LockCriticalSection(CRITICAL_SECTION* pCriticalSection):
m_pCriticalSection(pCriticalSection)
{
EnterCriticalSection(pCriticalSection);
}
/// \brief Destroy the object LockCriticalSection and
/// unlock the previously locked CRITICAL_SECTION.
///
///////////////////////////////////////////////////////////
virtual ~LockCriticalSection()
{
LeaveCriticalSection(m_pCriticalSection);
}
private:
CRITICAL_SECTION* m_pCriticalSection;
};
And this is the modified source code from your question:
do
{
{
LockCriticalSection lock(&criticalSectionToLock);
while (!commandExec->commands.empty())
{
commandExec->ExecuteCommand(commandExec->commands.front());
commandExec->commands.pop_front();
}
} // here the critical section is released
// suspend thread here
} while (commandExec->maintainCommandExecution);