简体   繁体   中英

C and pthreads: how can a mutex be referred to a particular variable?

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 ?

A (pthread) mutex isn't explicitly bound to a particular variable, it's just a general locking mechanism. It's up to you to make sure every action on that variable is properly surrounded by locks and unlocks.

Your program has a(n implicit) contract that only 1 thread may access dotstr.sum . The mutex helps you enforce it by making sure only 1 thread can have a lock on the mutex, but it won't force you to lock and unlock it everytime you do something with dotstr.sum .

Try, for example, commenting out the lock & unlock lines. The program will still compile and run, but the result may not be what you wanted it to be.

You can associate a mutex with anything, for example reading or writing from a file. But you must make sure that every access to the thing you want to lock is actually locked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM