DSL
Mutex_Win32Mutex.cpp
1 //@AUTOHEADER@BEGIN@
2 /***********************************************************************\
3 | Drift Standard Libraries v1.01 |
4 | Copyright 2010-2023 Drift Solutions / Indy Sams |
5 | Docs and more information available at https://www.driftsolutions.dev |
6 | This file released under the 3-clause BSD license, |
7 | see included DSL.LICENSE.TXT file for details. |
8 \***********************************************************************/
9 //@AUTOHEADER@END@
10 
11 #include <drift/dslcore.h>
12 
13 #if defined(WIN32)
14 
15 #include <drift/Mutex.h>
16 #include <drift/Threading.h>
17 #include <assert.h>
18 
19 DSL_Mutex_Win32Mutex::DSL_Mutex_Win32Mutex(int timeout, const char * name) {
20  refcnt = 0;
21  LockingThreadID = 0;
22  lock_timeout = timeout;
23  hMutex = CreateMutexA(NULL, FALSE, name);
24 }
25 
26 DSL_Mutex_Win32Mutex::~DSL_Mutex_Win32Mutex() {
27  CloseHandle(hMutex);
28 }
29 
30 bool DSL_Mutex_Win32Mutex::Lock() {
31  if (lock_timeout >= 0) {
32  return Lock(lock_timeout);
33  }
34 
35  DWORD ret = WaitForSingleObject(hMutex, INFINITE);
36  if (ret != WAIT_OBJECT_0) {
37  printf("Error while locking mutex! (%p, %p, %d, %d)\n", this, hMutex, ret, GetLastError());
38  assert(0);
39  }
40  LockingThreadID = GetCurrentThreadId();
41  refcnt++;
42  if (refcnt <= 0) { refcnt = 1; }
43  return true;
44 }
45 
46 bool DSL_Mutex_Win32Mutex::Lock(int timeout) {
47  DWORD ret = WaitForSingleObject(hMutex, timeout);
48  if (ret == WAIT_TIMEOUT) {
49  if (timeout > 1000) {
50  printf("Timeout while locking mutex! (%p, %p, %d)\n", this, hMutex, GetLastError());
51  }
52  return false;
53  }
54  if (ret != WAIT_OBJECT_0) {
55  printf("Error while locking mutex! (%p, %p, %d, %d)\n", this, hMutex, ret, GetLastError());
56  assert(0);
57  return false;
58  }
59  LockingThreadID = GetCurrentThreadId();
60  refcnt++;
61  if (refcnt <= 0) { refcnt = 1; }
62  return true;
63 }
64 
65 void DSL_Mutex_Win32Mutex::Release() {
66  refcnt--;
67  if (refcnt <= 0) {
68  LockingThreadID = 0;
69  }
70  if (ReleaseMutex(hMutex) == 0) {
71  printf("Error while unlocking mutex! (%p, %p, %d)\n", this, hMutex, GetLastError());
72  assert(0);
73  }
74 }
75 
76 THREADIDTYPE DSL_Mutex_Win32Mutex::LockingThread() {
77  return LockingThreadID;
78 }
79 
80 bool DSL_Mutex_Win32Mutex::IsLockMine() {
81  if (refcnt > 0 && GetCurrentThreadId() == LockingThreadID) { return true; }
82  return false;
83 }
84 
85 bool DSL_Mutex_Win32Mutex::IsLocked() {
86  if (refcnt > 0) { return true; }
87  return false;
88 }
89 
90 #endif