If I lock the same mutex in two different places in my function, and a context switch occurs when one thread is in one of them, and the second thread gets to the other one, will it be blocked?
I’ll try to give a simple example of what I mean, maybe it will be clearer.
Say I have the following code in a file test.c
int globalVar = 0;
void testMutex(pthread_mutex_t myMutex) {
pthread_mutex_lock(&myMutex);
globalVar++;
pthread_mutex_unlock(&myMutex);
printf("%s \n", "Doing some other stuff here");
pthread_mutex_lock(&myMutex);
globalVar--;
pthread_mutex_unlock(&myMutex);
}
and in a different file main.c, I have a main function which create two threads, thread1 and thread2, both running testMutex function.
thread1 is executed first, and while in the second part of the function (the — part, after printf), before mutex is unlocked, thread2 start running, from the function beginning.
will thread2 be able to execute globalVar++, or will it stay blocked, waiting for the mutex to be unlocked?
Thanks in advance!
The short answer is “yes”.
The pthread_mutex_lock documentation makes this pretty clear:
In other words, upon return from
pthread_mutex_lock, the mutex is “owned” by the thread. The system guarantees that at most one thread can “own” a single mutex at any time.