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

时间:2022-04-19 12:23:04

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.

我是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  

1 个解决方案

#1


2  

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

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

pthread_mutex_t mux;

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

然后你需要在其中一个.h文件中转发声明它:

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.

通常的惯例是你将.e文件中的前向声明放在.c文件中,但没有理由你不能把它放在一个不同的.h文件中;你只需要记住要包括哪个.h。确保包含定义变量的.h文件以及使用它的所有位置。

#1


2  

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

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

pthread_mutex_t mux;

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

然后你需要在其中一个.h文件中转发声明它:

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.

通常的惯例是你将.e文件中的前向声明放在.c文件中,但没有理由你不能把它放在一个不同的.h文件中;你只需要记住要包括哪个.h。确保包含定义变量的.h文件以及使用它的所有位置。