2

I’m new to pthread and mutex lock. I used them before but in a single file (main.c that creates the threads and locks are in the same file as functions and memory that use the locks). How to define mutex lock in C files that depend on each other? Ideally, I wish not to change the current structure.

main.c   // create threads, include `file1.h`
file1.h  
file1.c  // include `file1.h` and `lib.h`, extern a memory defined in `lib.c`
lib.h  
lib.c   // include `lib.h`, contain functions that malloc and dealloc memory, which need to be accessed by many threads  
Pippi
  • 2,451
  • 8
  • 39
  • 59

1 Answers1

4

You need to define the mutex in one of the .c files:

pthread_mutex_t mux;

and then you need to forward-declare it in one of the .h files:

extern pthread_mutex_t mux;

The normal convention is that you put the forward declaration in the .h file corresponding to the .c file, but there's no reason you couldn't put it in a different .h file; you just have to remember which .h to include. Make sure you include the .h file where the variable is defined and everywhere that it is used.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
kfsone
  • 23,617
  • 2
  • 42
  • 74