I am working on a multi-threaded program and wondering where to define a mutex.
Relevant information: the program has main.c, where we define a specific action in accordance with user input. main calls master_function, which is in the file with the name master.c. In the file, master.cwe create N threads along some other actions (it doesn't matter). A function called son_threads is called in the threads, which is located in the file son.c, and they must use the mutex when they enter, enter the critical region (editing several global variables to prevent the race condition). Another file I have is type.hwhere I define a few global variables that I need to use.
Mutex Announcement:
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
So, I tried to define mutex in mine type.hso that it appears in files son.c. When I try to compile, it gives me an error. This is correct since I am defining this mutex in multiple files.
But I'm sure that I can’t define the mutex in the file son.c, because every time I create this thread, the mutex will be initialized by default, not allowing me to use it correctly. Not sure about that.
A mutex must be a global variable in which N threads have access to it. So where should I put it?
I don’t know if I’ll explain it correctly. Trying my best.
source
share