zl程序教程

您现在的位置是:首页 >  其他

当前栏目

glibc: nptl: pthread_attr_init & pthread_attr_destroy;内存泄漏的可能

amp内存 可能 init 泄漏 pthread attr glibc
2023-09-14 09:13:12 时间

https://linux.die.net/man/3/pthread_attr_destroy
这里列的两个接口是一对,在上面手册里有说,如果不再需要attr对象,需要使用pthread_attr_destroy,来销毁这个对象。但是如果不详细看,其实看不出来为什么一定要成对使用。
When a thread attributes object is no longer required, it should be destroyed using the pthread_attr_destroy() function. Destroying a thread attributes object has no effect on threads that were created using that object.
但是没有说为什么?

从源代码看destroy函数里有这么一段代码

    {
      if (iattr->extension != NULL)
        {
          free (iattr->extension->cpuset);
          free (iattr->extension);
        }
    }

明显是调用了free释放内存。
所以如果在init和destroy不成对使用时,会有内存泄漏的风险。

这个extension是谁申请内存的呢?搜索glibc的代码会发现,下面这个函数有申请内存给extension。
pthread_attr_setaffinity_np
https://linux.die.net/man/3/pthread_attr_setaffinity_np
然后上面这个接口的使用手册也是没有提destroy的事情。所以还是有机会出现内存泄漏。
这也其实就容易让人挖坑,后人容易掉进去
假如一开始使用attr-init 函数时,不需要attr_setaffinity_np的操作。即使不销毁attr对象也是没有问题。这就造成一个坑。
后续随着业务的变更,有对affinity修改的需要,这时候如果没有销毁就造成内存泄漏。掉坑里。