I am confused as to mutex works on code segment or variables in a code segment.
In the example below, mutex will prevent two threads trying to access mysum at the same time either from func1 or func2 or only the code-segment between mutex lock and unlock is protected
.
.
pthread_mutex_t myMutex;
int mysum;
void func1(){
.
.
.
pthread_mutex_lock (&myMutex);
mysum--;
printf("Thread %ld did mysum=%d\n",id,mysum);
pthread_mutex_unlock (&myMutex);
.
.
}
void func2(){
.
.
.
mysum++;
pthread_mutex_lock (&myMutex);
mysum++;
printf("Thread %ld did mysum=%d\n",id,mysum);
pthread_mutex_unlock (&myMutex);
.
.
}
int main (int argc, char *argv[])
{
pthread_mutex_init(&myMutex, NULL);
.
.
pthread_create(&callThd1, &attr, func1, NULL);
pthread_create(&callThd2, &attr, func2, NULL);
pthread_create(&callThd3, &attr, func1, NULL);
pthread_create(&callThd4, &attr, func2, NULL);
pthread_create(&callThd5, &attr, func1, NULL);
pthread_create(&callThd6, &attr, func2, NULL);
.
.
pthread_mutex_destroy(&myMutex);
.
.
}
The mutex only provides mutual exclusion between the code sections that lie between
pthread_mutex_lock()andpthread_mutex_unlock()(these are known as critical sections).There’s no direct link between the mutex and the shared data it’s protecting – it is up to you to ensure that you only access the shared data with the appropriate mutex locked.