Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C where to define a mutex in a multithread program?

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.

like image 672
Alessandroempire Avatar asked Jun 15 '12 18:06

Alessandroempire


People also ask

How do you initialize mutex?

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 .

What is mutex multithreading?

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.

Can two threads lock the same mutex?

The short answer is "yes".

Can mutex be used across threads?

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.


1 Answers

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.

like image 192
Jens Gustedt Avatar answered Sep 18 '22 23:09

Jens Gustedt