| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
#include <config.h> |
| 21 |
|
| 22 |
|
| 23 |
#include "windows-recmutex.h" |
| 24 |
|
| 25 |
#include <errno.h> |
| 26 |
|
| 27 |
void |
| 28 |
glwthread_recmutex_init (glwthread_recmutex_t *mutex) |
| 29 |
{ |
| 30 |
mutex->owner = 0; |
| 31 |
mutex->depth = 0; |
| 32 |
InitializeCriticalSection (&mutex->lock); |
| 33 |
mutex->guard.done = 1; |
| 34 |
} |
| 35 |
|
| 36 |
int |
| 37 |
glwthread_recmutex_lock (glwthread_recmutex_t *mutex) |
| 38 |
{ |
| 39 |
if (!mutex->guard.done) |
| 40 |
{ |
| 41 |
if (InterlockedIncrement (&mutex->guard.started) == 0) |
| 42 |
|
| 43 |
glwthread_recmutex_init (mutex); |
| 44 |
else |
| 45 |
{ |
| 46 |
|
| 47 |
InterlockedDecrement (&mutex->guard.started); |
| 48 |
|
| 49 |
|
| 50 |
while (!mutex->guard.done) |
| 51 |
Sleep (0); |
| 52 |
} |
| 53 |
} |
| 54 |
{ |
| 55 |
DWORD self = GetCurrentThreadId (); |
| 56 |
if (mutex->owner != self) |
| 57 |
{ |
| 58 |
EnterCriticalSection (&mutex->lock); |
| 59 |
mutex->owner = self; |
| 60 |
} |
| 61 |
if (++(mutex->depth) == 0) |
| 62 |
{ |
| 63 |
mutex->depth--; |
| 64 |
return EAGAIN; |
| 65 |
} |
| 66 |
} |
| 67 |
return 0; |
| 68 |
} |
| 69 |
|
| 70 |
int |
| 71 |
glwthread_recmutex_trylock (glwthread_recmutex_t *mutex) |
| 72 |
{ |
| 73 |
if (!mutex->guard.done) |
| 74 |
{ |
| 75 |
if (InterlockedIncrement (&mutex->guard.started) == 0) |
| 76 |
|
| 77 |
glwthread_recmutex_init (mutex); |
| 78 |
else |
| 79 |
{ |
| 80 |
|
| 81 |
InterlockedDecrement (&mutex->guard.started); |
| 82 |
|
| 83 |
|
| 84 |
return EBUSY; |
| 85 |
} |
| 86 |
} |
| 87 |
{ |
| 88 |
DWORD self = GetCurrentThreadId (); |
| 89 |
if (mutex->owner != self) |
| 90 |
{ |
| 91 |
if (!TryEnterCriticalSection (&mutex->lock)) |
| 92 |
return EBUSY; |
| 93 |
mutex->owner = self; |
| 94 |
} |
| 95 |
if (++(mutex->depth) == 0) |
| 96 |
{ |
| 97 |
mutex->depth--; |
| 98 |
return EAGAIN; |
| 99 |
} |
| 100 |
} |
| 101 |
return 0; |
| 102 |
} |
| 103 |
|
| 104 |
int |
| 105 |
glwthread_recmutex_unlock (glwthread_recmutex_t *mutex) |
| 106 |
{ |
| 107 |
if (mutex->owner != GetCurrentThreadId ()) |
| 108 |
return EPERM; |
| 109 |
if (mutex->depth == 0) |
| 110 |
return EINVAL; |
| 111 |
if (--(mutex->depth) == 0) |
| 112 |
{ |
| 113 |
mutex->owner = 0; |
| 114 |
LeaveCriticalSection (&mutex->lock); |
| 115 |
} |
| 116 |
return 0; |
| 117 |
} |
| 118 |
|
| 119 |
int |
| 120 |
glwthread_recmutex_destroy (glwthread_recmutex_t *mutex) |
| 121 |
{ |
| 122 |
if (mutex->owner != 0) |
| 123 |
return EBUSY; |
| 124 |
DeleteCriticalSection (&mutex->lock); |
| 125 |
mutex->guard.done = 0; |
| 126 |
return 0; |
| 127 |
} |