// Copyright (c) 2012-2023 Wojciech Figat. All rights reserved.
#pragma once
#if PLATFORM_WIN32
#include "WindowsMinimal.h"
class Win32ConditionVariable;
///
/// Win32 implementation of a critical section. Shared between Windows and UWP platforms.
///
class FLAXENGINE_API Win32CriticalSection
{
friend Win32ConditionVariable;
private:
mutable Windows::CRITICAL_SECTION _criticalSection;
private:
Win32CriticalSection(const Win32CriticalSection&);
Win32CriticalSection& operator=(const Win32CriticalSection&);
public:
///
/// Initializes a new instance of the class.
///
Win32CriticalSection()
{
Windows::InitializeCriticalSectionEx(&_criticalSection, 100, 0x01000000);
}
///
/// Finalizes an instance of the class.
///
~Win32CriticalSection()
{
Windows::DeleteCriticalSection(&_criticalSection);
}
public:
///
/// Locks the critical section.
///
void Lock() const
{
// Spin first before entering critical section, causing ring-0 transition and context switch
if (Windows::TryEnterCriticalSection(&_criticalSection) == 0)
{
Windows::EnterCriticalSection(&_criticalSection);
}
}
///
/// Attempts to enter a critical section without blocking. If the call is successful, the calling thread takes ownership of the critical section.
///
/// True if calling thread took ownership of the critical section.
bool TryLock() const
{
return Windows::TryEnterCriticalSection(&_criticalSection) != 0;
}
///
/// Releases the lock on the critical section.
///
void Unlock() const
{
Windows::LeaveCriticalSection(&_criticalSection);
}
};
#endif