This topic is now archived and is closed to further replies.

A good Mutex class

This topic is 5110 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am having trouble writing a good Mutex class, due to the fact that I know not of an instruction in the x86 ISA to do a Mutex lock, and doing so is more than one instruction. What I am trying to do is illustrated here:

int _lock;


void lock(){while(_lock);_lock++;}
void unlock(){lock=0;}

That''s all, but the problem is with the lock function, without even breaking it down to assembly one can find a problem:
while(_lock)              _lock++; 
/*             ^                     ^ 
         Thread changes          Now two callers have the lock
          and Mutex is
Thanks, even just source code would be great ~SPH

Share this post

Link to post
Share on other sites

__asm {
mov ebx,lockcountptr
mov eax,1
; I think xchg automatically does a lock, but, just in case...
lock xchg [ebx],eax
test eax,eax
je locked
; Somehow call Windows Sleep(0);
jmp retry

;unlock just writes 0 to lockcount


// header
class E3DMutex
HANDLE mutex;


BOOL Obtain(DWORD timeout = INFINITE);
void Release();

// cpp
// Security is ignored on XBox, and must be NULL
#ifndef _XBOX
SECURITY_ATTRIBUTES g_Security = {12, 0, 1};
void *g_Security = NULL;

mutex = CreateMutex(&g_Security, FALSE, NULL);


BOOL E3DMutex::Obtain(DWORD timeout)
DWORD res;

res = WaitForSingleObject(mutex, timeout);
if (res == WAIT_OBJECT_0)
return TRUE;
return FALSE;

void E3DMutex::Release()

Share this post

Link to post
Share on other sites