C where to define a mutex in a multi-threaded program?

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.

+5
source share
3 answers

Just declare a variable in the file .h

extern pthread_mutex_t mutex1;

C. , C.

POSIX . .h.

+6

, son.c, , , , . .

. , . , . extern pthread_mutex_t mutex1; , , son.c, .

+2

If you must have a global variable and share it between the modules in 'C', I think this is typical of a declaration in the included file. In the old days, we would use some kind of magic macro like "GLOBAL" in the .h file as "extern", and basically we would redefine GLOBAL as nothing that would be declared basically.

#ifndef _TYPES_H
#define _TYPES_H

    // types.h

    #ifndef GLOBAL
    #   define GLOBAL extern
    #endif

    GLOBAL my_global mutex;


#endif
+1
source

All Articles