Alessandroempire
Alessandroempire

Reputation: 1699

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.

Upvotes: 7

Views: 11192

Answers (3)

Jens Gustedt
Jens Gustedt

Reputation: 78923

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.

Upvotes: 9

twalberg
twalberg

Reputation: 62389

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.

This is not correct. Put the mutex definition in that file, but outside the thread function. It will be initialized at program startup, but not on each new thread. You can put extern pthread_mutex_t mutex1; in one of the header files so that any users of the mutex that aren't in son.c know about the mutex.

Upvotes: 2

user1459369
user1459369

Reputation: 11

If you must have a global variable and share it between modules in 'C' I think it's typical to have it declared in an include file. In the old days we would use some magic macro like "GLOBAL" in the .h file as "extern" and in the main we'd re-define GLOBAL as nothing such that it would be declared in main.

#ifndef _TYPES_H
#define _TYPES_H

    // types.h

    #ifndef GLOBAL
    #   define GLOBAL extern
    #endif

    GLOBAL my_global mutex;


#endif

Upvotes: 1

Related Questions