]> pd.if.org Git - pdclib/blobdiff - platform/win32/functions/threads/mtx_lock.c
win32: initial pass at thread support
[pdclib] / platform / win32 / functions / threads / mtx_lock.c
diff --git a/platform/win32/functions/threads/mtx_lock.c b/platform/win32/functions/threads/mtx_lock.c
new file mode 100644 (file)
index 0000000..70af8ae
--- /dev/null
@@ -0,0 +1,40 @@
+#ifndef REGTEST\r
+#include <threads.h>\r
+#include <windows.h>\r
+\r
+int mtx_lock(mtx_t *mtx)\r
+{\r
+    DWORD myId = GetCurrentThreadId();\r
+\r
+    if(mtx->_ThreadId == myId) {\r
+        mtx->_NestCount++;\r
+        return thrd_success;\r
+    }\r
+\r
+    DWORD res = InterlockedIncrement(&mtx->_State);\r
+    if(res == 0) {\r
+        mtx->_ThreadId = myId;\r
+        return thrd_success;\r
+    }\r
+\r
+    // If that increment didn't leave the state == 0, then we have contention\r
+    //  -> block on the wait event handle\r
+    DWORD rv = WaitForSingleObject(mtx->_WaitEvHandle, INFINITE);\r
+    if(rv != WAIT_OBJECT_0) \r
+        return thrd_error;\r
+\r
+    // We now own the mutex - so set it up for our use\r
+    mtx->_ThreadId = myId;\r
+    return thrd_success;\r
+}\r
+#endif\r
+\r
+#ifdef TEST\r
+#include <_PDCLIB_test.h>\r
+\r
+int main( void )\r
+{\r
+    return TEST_RESULTS;\r
+}\r
+\r
+#endif
\ No newline at end of file