I am a little bit confused trying to implement a very simple mutex (lock) in C. I understand that a mutex is similar to a binary semaphore, except that the mutex also enforces the constraint that the thread that releases the lock, must be the same thread that most recently acquired it. I am confused on how the ownership is kept track of?
This is what I have so far. Keep in mind that it is not completed yet, and is suppose to be really simple (uniprocessor, no recursion on mutex, disabling interrupts as mutual exclusion method, etc).
struct mutex {
char *mutexName;
volatile int inUse;
};
I believe I should add in another member variable, i.e., whoIsOwner, but I am kind of confused as what to store there. I assume it has to be something that can uniquely identify the thread trying to call the lock? Is this correct?
I have a thread structure in place that has a “char *threadName” member variable (along with others), but I’m not sure how I would access this from within the mutex implementation.
Any pointers/hints/ideas would be appreciated.
You could implement the mutex as an atomic integer which is
0when unlocked, and which takes the value of the locking thread’s ID to indicate it’s locked. Of course access to the variable has to be atomic, and suitably fenced to prevent reordering (acquire-release fence pairs suffice).Ultimately you can of course never prevent yourself from shooting yourself in the foot; if you really want you can overwrite the mutex’s memory by force from another thread, or something like that. You’ll only get the correct behaviour if you use the tools correctly. With that in mind, you might be satisfied with a simple bool for the locking variable.