DSL
Mutex_Win32CS.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_Win32CS::DSL_Mutex_Win32CS(int timeout) {
20  refcnt = 0;
21  LockingThreadID = 0;
22  lock_timeout = timeout;
23  memset(&cs, 0, sizeof(cs));
24  InitializeCriticalSection(&cs);
25 }
26 
27 DSL_Mutex_Win32CS::~DSL_Mutex_Win32CS() {
28  assert(refcnt <= 0);
29  DeleteCriticalSection(&cs);
30 }
31 
32 bool DSL_Mutex_Win32CS::Lock() {
33  if (lock_timeout >= 0) {
34  return Lock(lock_timeout);
35  }
36 
37  EnterCriticalSection(&cs);
38  LockingThreadID = GetCurrentThreadId();
39  refcnt++;
40  if (refcnt <= 0) { refcnt = 1; }
41  return true;
42 }
43 
44 bool DSL_Mutex_Win32CS::Lock(int timeout) {
45  int left = timeout;
46  BOOL amIn = TryEnterCriticalSection(&cs);
47  while (!amIn) {
48  if (left > 0) {
49  safe_sleep(100, true);
50  left -= 100;
51  amIn = TryEnterCriticalSection(&cs);
52  } else {
53  if (timeout > 1000) {
54  printf("Timeout while locking mutex! (%p, %p, %d)\n", this, &cs, GetLastError());
55  }
56  return false;
57  }
58  }
59  LockingThreadID = GetCurrentThreadId();
60  refcnt++;
61  if (refcnt <= 0) { refcnt = 1; }
62  return true;
63 }
64 
65 void DSL_Mutex_Win32CS::Release() {
66  assert(refcnt > 0);
67  refcnt--;
68  if (refcnt <= 0) {
69  LockingThreadID = 0;
70  }
71  LeaveCriticalSection(&cs);
72 }
73 
74 THREADIDTYPE DSL_Mutex_Win32CS::LockingThread() {
75  return LockingThreadID;
76 }
77 
78 bool DSL_Mutex_Win32CS::IsLockMine() {
79  if (refcnt > 0 && GetCurrentThreadId() == LockingThreadID) { return true; }
80  return false;
81 }
82 
83 bool DSL_Mutex_Win32CS::IsLocked() {
84  if (refcnt > 0) { return true; }
85  return false;
86 }
87 
88 #endif