feature: implement win32 mutex synchronization primitive

This commit is contained in:
MechSlayer 2025-09-05 15:16:32 +02:00
parent 37c59b003c
commit cd36e689a6

View file

@ -0,0 +1,99 @@
#include <drang/alloc.h>
#include <drang/sync.h>
#define WIN32_LEAN_AND_MEAN
#include <stdbool.h>
#include <windows.h>
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();
}