X-Git-Url: https://pd.if.org/git/?p=pdclib;a=blobdiff_plain;f=platform%2Fwin32%2Ffunctions%2Fthreads%2Fmtx_lock.c;h=b76c8ec5ad66d7c0efa4c3208f5894b7f918a754;hp=70af8ae35bd7cd65c7785527544d7cf7778e2776;hb=da0f3f353d417fed71f358a48d5d5394145e460d;hpb=639bad513ab9399ed9a8c588a476a10dbe6c9478 diff --git a/platform/win32/functions/threads/mtx_lock.c b/platform/win32/functions/threads/mtx_lock.c index 70af8ae..b76c8ec 100644 --- a/platform/win32/functions/threads/mtx_lock.c +++ b/platform/win32/functions/threads/mtx_lock.c @@ -6,31 +6,25 @@ int mtx_lock(mtx_t *mtx) { DWORD myId = GetCurrentThreadId(); - if(mtx->_ThreadId == myId) { + if(mtx->_ThreadId == (long) myId) { mtx->_NestCount++; return thrd_success; } - DWORD res = InterlockedIncrement(&mtx->_State); - if(res == 0) { - mtx->_ThreadId = myId; - return thrd_success; - } + for(;;) { + LONG prev = InterlockedCompareExchange(&mtx->_ThreadId, myId, 0); + if(prev == 0) + return thrd_success; - // If that increment didn't leave the state == 0, then we have contention - // -> block on the wait event handle - DWORD rv = WaitForSingleObject(mtx->_WaitEvHandle, INFINITE); - if(rv != WAIT_OBJECT_0) - return thrd_error; - - // We now own the mutex - so set it up for our use - mtx->_ThreadId = myId; - return thrd_success; + DWORD rv = WaitForSingleObject(mtx->_WaitEvHandle, INFINITE); + if(rv != WAIT_OBJECT_0) + return thrd_error; + } } #endif #ifdef TEST -#include <_PDCLIB_test.h> +#include "_PDCLIB_test.h" int main( void ) {