需要释放互斥锁吗?
我有一个非常简单的(示例)C 程序,如下所示。我想确保释放任何必要的资源,以便 valgrind 不会抱怨。我需要释放 mutex1 吗?或者在程序终止之前做任何事情?或者是mutex1没有分配内存?
02 pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
03 int counter=0;
04
05 /* Function C */
06 void functionC()
07 {
08 pthread_mutex_lock( &mutex1 );
09 counter++
10 pthread_mutex_unlock( &mutex1 );
11 }
I have a very simple (sample) C program as follows. I want to ensure I release any resources necessary so that valgrind does not complain. Do I need to free mutex1? Or do anything before the program terminates? Or is the mutex1 not allocate memory?
02 pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
03 int counter=0;
04
05 /* Function C */
06 void functionC()
07 {
08 pthread_mutex_lock( &mutex1 );
09 counter++
10 pthread_mutex_unlock( &mutex1 );
11 }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,这样就很好。没有必要对静态分配的互斥体使用 pthread_mutex_destroy。
No, it is fine as it is. It is not necessary to use pthread_mutex_destroy on a statically allocated mutex.
不,您不需要释放
mutex1
。PTHREAD_MUTEX_INITIALIZER
是一个隐藏结构体初始化的宏。No, you don't need to free
mutex1
.PTHREAD_MUTEX_INITIALIZER
is a macro that hides a struct initialisation.代码中的 mutex1 是一个全局变量,而不是堆分配的变量。您不需要释放它。当您的应用程序终止时,操作系统将释放您的应用程序使用的所有资源。
mutex1 in your code is a global variable rather than a heap-allocated variable. You do not need to free it. The OS will free all resources that your app use when you app terminate.