]> pd.if.org Git - pdclib/blob - platform/win32/functions/threads/mtx_lock.c
win32: initial pass at thread support
[pdclib] / platform / win32 / functions / threads / mtx_lock.c
1 #ifndef REGTEST\r
2 #include <threads.h>\r
3 #include <windows.h>\r
4 \r
5 int mtx_lock(mtx_t *mtx)\r
6 {\r
7     DWORD myId = GetCurrentThreadId();\r
8 \r
9     if(mtx->_ThreadId == myId) {\r
10         mtx->_NestCount++;\r
11         return thrd_success;\r
12     }\r
13 \r
14     DWORD res = InterlockedIncrement(&mtx->_State);\r
15     if(res == 0) {\r
16         mtx->_ThreadId = myId;\r
17         return thrd_success;\r
18     }\r
19 \r
20     // If that increment didn't leave the state == 0, then we have contention\r
21     //  -> block on the wait event handle\r
22     DWORD rv = WaitForSingleObject(mtx->_WaitEvHandle, INFINITE);\r
23     if(rv != WAIT_OBJECT_0) \r
24         return thrd_error;\r
25 \r
26     // We now own the mutex - so set it up for our use\r
27     mtx->_ThreadId = myId;\r
28     return thrd_success;\r
29 }\r
30 #endif\r
31 \r
32 #ifdef TEST\r
33 #include <_PDCLIB_test.h>\r
34 \r
35 int main( void )\r
36 {\r
37     return TEST_RESULTS;\r
38 }\r
39 \r
40 #endif