I am working on a multi-thread program, and have a question about where to define the mutex.
Relevant information: the program has a main.c where we determinate a specific action according to the user input. main calls a master_function which is located in a file named master.c. In the master.c file we create the N threads along some other actions (not relevant). The threads call a function named son_threads which is located in a son.c file and they need to use a mutex when they enter enter a critical region (editing several global variable to prevent race condition). Another file I have is a type.h where I define several global variables I need to use.
The declaration of mutex is:
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
So I tried to define the mutex in my type.h so it’s visible to the son.c files. When I try to compile it gives me error. Which is correct since I am defining that mutex in several files.
But I am pretty sure I cant define the mutex in the son.c file because each time I create that thread, the mutex will be initialized to its default setting, not allowing me to use it properly. Not sure about this.
The mutex has to be a global variable, where the N threads have access to it. So where am I supposed to put it?
I dont know if I am explaining myself right. Trying my best.
Just declare your variable in the
.hfileand keep the definition with the initialization in the C file. This is as it is meant by the C standard(s).
For POSIX, the initialization of the mutex with static storage is really important. So that definition can’t live in a
.hfile.