I am new to multi-threading and I have extreme difficulty wrapping my head around mutual exclusion.
So here is the prototype for pthread_mutex_lock
int pthread_mutex_lock(pthread_mutex_t *mutex);
The man page says that The mutex object referenced by mutex shall be locked by calling pthread_mutex_lock().
First of all my understanding is that you use mutex locking to lock a shared resource so that only one thread can access it at any time. For the sake of argument, let's say that the shared resource is a global variable called myVariable
. Now if we want to lock myVariable, I should be able to use a locking mechanism to lock myVariable
, but what does it mean to lock a mutex object
? I mean if I call pthread_mutex_lock(&someMutex)
, am I locking myVariable
or something else?
All to say that if I want to use mutual exclusion, shouldn't I be able to do something like pthread_mutex_lock(myVariable)
as opposed to doing pthread_mutex_lock(&someMutex)
?
Also how does this someMutex
object correspond to myVariable? How does this someMutex
object lock access to myVariable
?
P.S. Assume that I have declared someMutex
before itself.
P.P.S. I had a feeling that this question maybe broad, but then again, it shouldn't be since I am asking about something that actually has a specific answer(correct me if I am wrong).