Skip to content

Instantly share code, notes, and snippets.

@varhub
Created November 14, 2019 16:54
Show Gist options
  • Save varhub/4ee788f69470d800b93c7275b0e687c8 to your computer and use it in GitHub Desktop.
Save varhub/4ee788f69470d800b93c7275b0e687c8 to your computer and use it in GitHub Desktop.
C++ Windows: fixing stupidity of `CRITICAL_SECTION`. Bringing back C++ standards to non-standard broken class.
#pragma once
#ifndef CRITICAL_SECTION_GUARD_H_
#define CRITICAL_SECTION_GUARD_H_
#include <windows.h>
// (c) 2019 <[email protected]>
// Released under BSD-3 clause.
class CriticalSectionGuard {
private:
CRITICAL_SECTION *_mutexPtr;
public:
CriticalSectionGuard(CRITICAL_SECTION *mutex)
: _mutexPtr(mutex)
{
EnterCriticalSection( _mutexPtr );
}
~CriticalSectionGuard()
{
LeaveCriticalSection( _mutexPtr );
}
};
class CriticalSectionRAII {
private:
CRITICAL_SECTION _mutex;
public:
CriticalSectionRAII() { InitializeCriticalSection( &_mutex ); }
~CriticalSectionRAII() { DeleteCriticalSection( &_mutex ); }
operator CRITICAL_SECTION*() { return &_mutex; }
// CRITICAL_SECTION* operator&() { return &_mutex; } // Enable it with caution. Backward compatibility is a trap ;)
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment