Is it preferred to use a global pthread_mutex_t in C projects?

Viewed 55

How is pthread_mutex_t used for a multi source C project.

Is there a global pthread_mutex_t in a header file or does each source file defines it's own? How many times pthread_mutex_init is used? only once per mutex?

So if we use a global mutex, we only need to use pthread_mutex_init once in the beginning of main?

2 Answers

How is pthread_mutex_t used for a multi source C project.

It really depends on the project itself and what the code needs to do. There's no "standard" way of doing this.

Is there a global pthread_mutex_t in a header file or does each source file define it's own?

Again, it depends on what is needed. There is no rule saying that there should only be one global mutex or that there should be one mutex per source file. It depends. If a resource needs to be managed by different files then a unique global mutex can be used. If another resource needs to be managed only by the code that is defined in a single source file then there's no need to make it available globally (and it can be defined static).

Yes, pthread_mutex_init should be used once per mutex.

So if we use a global mutex, we only need to use pthread_mutex_init once in the beginning of main?

Yes. That would be one way to do it.

Another, perhaps better approach is to just initialize the variable at its definition:

pthread_mutex_t my_mutex = PTHREAD_MUTEX_INITIALIZER;
// or
static pthread_mutex_t my_mutex = PTHREAD_MUTEX_INITIALIZER;

This way there's no need to call pthread_mutex_init and you don't risk forgetting it.

Generally, you should expect to use one mutex for each "unit" of shared state that's accessed by multiple threads. If one such unit is global state, then you would expect to have a global mutex alongside it, and it can be statically initialized with PTHREAD_MUTEX_INITIALIZER. If it's a data structure that can exist in multiple instances in allocated storage, you normally want to place the mutex protecting it inside the data structure itself, and initialize it with pthread_mutex_init when it's created, before its existence is exposed to multiple threads.

Related