如何在相互依赖的C文件中定义pthread和互斥锁?

How to define pthread and mutex lock in C files that depend on each other?

我是 pthread 和互斥锁的新手。我以前使用过它们,但是在一个文件中(创建线程和锁的 main.c 与使用锁的函数和内存在同一个文件中)。如何在相互依赖的C文件中定义互斥锁?理想情况下,我不希望更改当前结构。

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  

您需要在 .c 个文件之一中定义互斥量:

pthread_mutex_t mux;

然后您需要在 .h 文件之一中转发声明它:

extern pthread_mutex_t mux;

通常的约定是将前向声明放在 .c 文件对应的 .h 文件中,但没有理由不能将其放在不同的 .h ] 文件;您只需要记住要包含哪个 .h 即可。确保包含定义变量的 .h 文件以及使用它的所有地方。