diff --git a/Source/DrangPlatform/Source/win32/sync/mutex.c b/Source/DrangPlatform/Source/win32/sync/mutex.c new file mode 100644 index 0000000..80474b6 --- /dev/null +++ b/Source/DrangPlatform/Source/win32/sync/mutex.c @@ -0,0 +1,99 @@ +#include +#include + +#define WIN32_LEAN_AND_MEAN +#include +#include + + +struct drang_mutex +{ + CRITICAL_SECTION cs; + bool initialized; +}; + +size_t drang_mutex_size(void) +{ + return sizeof(struct drang_mutex); +} + +int drang_mutex_new(struct drang_mutex **mutex) +{ + struct drang_mutex *m = NULL; + DRANG_BEGIN_TRY(); + + DRANG_CHECK(mutex != NULL, DRANG_EINVAL); + + m = DRANG_TRY_ALLOC_T(struct drang_mutex); + + DRANG_TRY(drang_mutex_init(m)); + + DRANG_RETURN_IN(mutex, m); + + DRANG_CATCH(_) + { + if (m != NULL) { + drang_free(m); + } + } + DRANG_END_TRY(); +} + +void drang_mutex_free(struct drang_mutex *mutex) +{ + if (mutex == NULL) { + return; + } + + drang_mutex_fini(mutex); + drang_free(mutex); +} + +int drang_mutex_init(struct drang_mutex *mutex) +{ + DRANG_BEGIN_TRY(); + + DRANG_CHECK(mutex != NULL, DRANG_EINVAL); + DRANG_CHECK(!mutex->initialized, DRANG_EBUSY); + + InitializeCriticalSection(&mutex->cs); + mutex->initialized = true; + + DRANG_END_TRY_IGNORE(); +} + +void drang_mutex_fini(struct drang_mutex *mutex) +{ + if (mutex == NULL) { + return; + } + + DeleteCriticalSection(&mutex->cs); + mutex->initialized = false; +} + +int drang_mutex_lock(struct drang_mutex *mutex) +{ + DRANG_BEGIN_TRY(); + + DRANG_CHECK(mutex != NULL, DRANG_EINVAL); + DRANG_CHECK(mutex->initialized, DRANG_EINVAL); + + EnterCriticalSection(&mutex->cs); + + DRANG_END_TRY_IGNORE(); +} + +int drang_mutex_unlock(struct drang_mutex *mutex) +{ + DRANG_BEGIN_TRY(); + + DRANG_CHECK(mutex != NULL, DRANG_EINVAL); + DRANG_CHECK(mutex->initialized, DRANG_EINVAL); + + LeaveCriticalSection(&mutex->cs); + + DRANG_RETURN(); + + DRANG_END_TRY_IGNORE(); +}