Implementing a Mutex Lock in C

Posted by Adam on Stack Overflow See other posts from Stack Overflow or by Adam
Published on 2010-04-21T01:51:39Z Indexed on 2010/04/21 1:53 UTC
Read the original article Hit count: 372

Filed under:
|
|

I'm trying to make a really mutex in C and for some reason I'm getting cases where two threads are getting the lock at the same time, which shouldn't be possible. Any ideas why it's not working?

void mutexLock(mutex_t *mutexlock, pid_t owner)
{
int failure;
while(mutexlock->mx_state == 0 || failure || mutexlock->mx_owner != owner)
{
    failure = 1;
    if (mutexlock->mx_state == 0)
    {
        asm(
        "test:"
        "movl    $0x01,%%eax\n\t"      // move 1 to eax
        "xchg    %%eax,%0\n\t"         // try to set the lock bit
        "mov     %%eax,%1\n\t"         // export our result to a test var
        "test    %%eax,%%eax\n\t"
        "jnz     test\n\t"
        :"=r"(mutexlock->mx_state),"=r"(failure)
        :"r"(mutexlock->mx_state)
        :"%eax"
        );
    }
    if (failure == 0)
    {
        mutexlock->mx_owner = owner; //test to see if we got the lock bit
    }
    } 
}

© Stack Overflow or respective owner

Related posts about mutex

Related posts about c