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.
Use pthread_mutex_init(3C) to initialize the mutex pointed at by mp to its default value or to specify mutex attributes that have already been set with pthread_mutexattr_init() . The default value for mattr is NULL .
Mutex is a synchronization primitive that grants exclusive access to the shared resource to only one thread. If a thread acquires a mutex, the second thread that wants to acquire that mutex is suspended until the first thread releases the mutex.
The short answer is "yes".
Mutexes can synchronize threads within the same process or in other processes. Mutexes can be used to synchronize threads between processes if the mutexes are allocated in writable memory and shared among the cooperating processes (see mmap(2)), and have been initialized for this task.
Just declare your variable in the .h
file
extern pthread_mutex_t mutex1;
and 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 .h
file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With