简体   繁体   English

释放包含 pthread_mutex_t 的结构 memory 时是否需要调用 pthread_mutex_destroy

[英]Is it neccessary to call the pthread_mutex_destroy when free a struct memory which contains a pthread_mutex_t

Let's say I have a sruct:假设我有一个 sruct:

typedef struct peer_info {
        int ip;
        int port;
        int offset;
        pthread_mutex_t mutex;
} peer_info;

and then I use the struct and free the struct like below:然后我使用结构并释放结构,如下所示:

peer_info* p_info = (peer_info*)malloc(sizeof(peer_info));
pthread_mutex_init(&p_info->mutex, NULL);

/* do some work on the p_info */


// need I call the pthread_mutex_destory(&p_info->mutex); ?
free(p_info);

I checke the glibc ntpl souce code, it seems i don't need to explictly call pthread_mutex_destory() since there is not memroy allocted on the pthread_mutex_t , which is a union type.我检查了 glibc ntpl 源代码,似乎我不需要显式调用pthread_mutex_destory()因为在pthread_mutex_t上没有分配内存,这是一个联合类型。

Yes.是的。 If you've initialised the mutex with pthread_mutex_init() , it should be destroyed with pthread_mutex_destroy() before freeing the memory.如果您已使用pthread_mutex_init()初始化了互斥锁,则应在释放 memory 之前使用pthread_mutex_destroy()将其销毁。

The POSIX standard contemplates both implementations where the mutex entirely resides in the pthread_mutex_t type, and implementations where the type includes only a reference to some externally-allocated mutex object. POSIX 标准考虑了互斥锁完全驻留在pthread_mutex_t类型中的实现,以及类型仅包含对某些外部分配的互斥锁 object 的引用的实现。 This is reinforced by the fact that pthread_mutex_init() is allowed to fail due to various resource-exhaustion reasons.由于各种资源耗尽原因,允许pthread_mutex_init()失败这一事实强化了这一点。

Calling pthread_mutex_destroy() where appropriate ensures your code is portable to the latter kinds of implementations.在适当的地方调用pthread_mutex_destroy()可确保您的代码可移植到后一种实现。

I find the answer on Richard's APUE book.我在 Richard 的 APUE 书中找到了答案。

A mutex variable is represented by the pthread_mutex_t data type.互斥变量由 pthread_mutex_t 数据类型表示。 Before we can use a mutex variable, we must first initialize it by either setting it to the constant PTHREAD_MUTEX_INITIALIZER (for statically allocated mutexes only) or calling pthread_mutex_init.在我们可以使用互斥体变量之前,我们必须首先通过将其设置为常量 PTHREAD_MUTEX_INITIALIZER(仅适用于静态分配的互斥体)或调用 pthread_mutex_init 来初始化它。 If we allocate the mutex dynamically (by calling malloc, for example), then we need to call pthread_mutex_destroy before freeing the memory.如果我们动态分配互斥锁(例如通过调用 malloc),那么我们需要在释放 memory 之前调用 pthread_mutex_destroy。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM