Jump to content
  • Advertisement

Archived

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

ShmeeBegek

A good Mutex class

This topic is 5275 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
Advertisement

I think I''m going to break down and go with the windows synchronization functions, still if there is a solution to this I would love to see it .

Thanks again, ~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

I''m avoiding OS-Specific functions wherever possible, so that porting the project will be easier in the future.

But ''tis fine, I''ve got it working now and all is well, Thanks ~SPH

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!