In this code an example of the use of mutex is showed. In particular, the mutex is first declared before the main
:
pthread_mutex_t mutexsum;
The particular variable to be "protected" by the mutex is dotstr.sum
in the global structure dotstr
: every thread writes on it after having acquired a lock
. The correspondant code is:
pthread_mutex_lock (&mutexsum);
dotstr.sum += mysum;
printf("Thread %ld did %d to %d: mysum=%f global sum=%f\n",offset,start,end,mysum,dotstr.sum);
pthread_mutex_unlock (&mutexsum);
I have compiled the code and it obviously works, but I don't know mutexes very well. So, how can the program be aware that the "general" mutex mutexsum
is applied just on the dotstr.sum
variable?
There are many other global variables which can be locked. Why there is not an explicit relation in the code between the mutex mutexsum
and the variable I want to lock, dotstr.sum
?