11#define MUTEX_TYPE HANDLE
14#define MUTEX_TYPE mtx_t
49 if (handle_ptr != NULL)
79 HANDLE hMutex = CreateMutex(NULL, FALSE, NULL);
90 printf(
"Error! Out of memory saving mutex handle.\n");
96 DWORD lastError = GetLastError();
97 printf(
"Error (0x%x)! Failed to create a mutex.\n", lastError);
101 int err = mtx_init(&mutex_handle, mtx_plain);
102 if (err == thrd_success)
105 if (mutex->
handle != NULL)
111 printf(
"Error! Out of memory saving mutex handle.\n");
112 mtx_destroy(&mutex_handle);
117 printf(
"Error! Failed to create a mutex.\n");
130 bool destroyed =
false;
132 if (mutex != NULL && mutex->
handle != NULL)
136 if (CloseHandle(hMutex))
142 DWORD lastError = GetLastError();
143 printf(
"Error (0x%x)! Failed to destroy the mutex.\n", lastError);
147 mtx_destroy(&mutex_handle);
164 if (mutex != NULL && mutex->
handle != NULL)
168 DWORD waitResult = WaitForSingleObject(hMutex, INFINITE);
169 if (waitResult == WAIT_OBJECT_0)
173 else if (waitResult == WAIT_ABANDONED)
175 printf(
"Error! While attempting to lock a mutex, it was found to be abandoned.\n");
179 int err = mtx_lock(&mutex_handle);
180 if (err == thrd_success)
186 printf(
"Error! Failed to lock a mutex.\n");
199 bool unlocked =
false;
201 if (mutex != NULL && mutex->
handle != NULL)
205 if (ReleaseMutex(hMutex))
211 DWORD lastError = GetLastError();
212 printf(
"Error (0x%x)! Failed to unlock a mutex.\n", lastError);
216 int err = mtx_unlock(&mutex_handle);
217 if (err == thrd_success)
223 printf(
"Error! Failed to unlock a mutex.\n");
static void _deallocate_mutex_handle(void *handle)
Helper function to deallocate memory that contained a mutex handle. The mutex handle itself should be...
bool mutex_destroy(Mutex *mutex)
Destroy a previously created mutex.
bool mutex_unlock(Mutex *mutex)
Unlock a previously locked mutex.
bool mutex_create(Mutex *mutex)
Create a new mutex, which is initially not owned.
static void * _allocate_mutex_handle(MUTEX_TYPE handle)
Helper function to allocate memory from the heap in which to store the given mutex handle....
static MUTEX_TYPE _get_mutex_handle(void *handle)
Helper function to retrieve the mutex handle from the given memory pointer.
bool mutex_lock(Mutex *mutex)
Lock a previously created and unlocked mutex. This will block if the mutex is already locked by some ...
Declaration of the Mutex structure and supporting functions for working with mutexes.
Represents a handle to a mutex. Call mutex_create() to create the mutex and mutex_destroy() to destro...
void * handle
An opaque value that represents the operating system-specific mutex.