HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Self-written Mutex for 2+ Threads

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
mutexwrittenthreadsforself

Problem

I have written the following code, and so far in all my tests it seems as if I have written a working Mutex for my 4 Threads, but I would like to get someone else's opinion on the validity of my solution.

typedef struct Mutex{
    int turn;
    int * waiting;
    int num_processes;
} Mutex;

void enterLock(Mutex * lock, int id){   
    int i;
    for(i = 0; i num_processes; i++){
        lock->waiting[id] = 1;
        if (i != id && lock->waiting[i])
            i = -1;
        lock->waiting[id] = 0;
    }
    printf("ID %d Entered\n",id);
}

void leaveLock(Mutex * lock, int id){
    printf("ID %d Left\n",id);
    lock->waiting[id] = 0;
}

Solution

Broken

If you call enterLock() with id 0 followed by enterLock() with id 1 (on another thread perhaps), both calls will succeed. Since your function doesn't change the state of the mutex, it isn't surprising. Perhaps you meant to leave lock->waiting[id] at 1 instead of 0? Note, even if you did that, it wouldn't be enough to fix the mutex.

Also, what is the turn variable used for?
Spinlock, not mutex

Technically, what you are doing is a spinlock. A real mutex should efficiently wait for its turn instead of spinning in a loop.

Context

StackExchange Code Review Q#103938, answer score: 6

Revisions (0)

No revisions yet.