C where to define a mutex in a multithread program? C where to define a mutex in a multithread program? unix unix

C where to define a mutex in a multithread program?


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.


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.


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