Archived

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
            locked. 
*/
Thanks, even just source code would be great ~SPH

Share this post


Link to post
Share on other sites

__asm {
mov ebx,lockcountptr
retry:
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
locked:
ret
}

;unlock just writes 0 to lockcount

or

// header
class E3DMutex
{
public:
HANDLE mutex;

E3DMutex();
~E3DMutex();

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};
#else
void *g_Security = NULL;
#endif

E3DMutex::E3DMutex()
{
mutex = CreateMutex(&g_Security, FALSE, NULL);
}

E3DMutex::~E3DMutex()
{
CloseHandle(mutex);
}

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

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

void E3DMutex::Release()
{
ReleaseMutex(mutex);
}

Share this post


Link to post
Share on other sites