在循环中调用 pthread_cancel() 显示内存使用量增加

标签 c linux memory-leaks pthreads

我正在用我的 C 测试代码测试 pthread_cancel() 功能。这不是我正在使用的确切代码,而是用于解释的简化形式。

int main(argc, char *argvp[])
{
    while(1) {
        start_thread();
        sleep(5);
        end_thread();
    }
}

void my_thread(void *arg) 
{
     printf("in my thread\n");
     pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
     return 0;
}

void start_thread()
{
    pthread_create(&my_id, NULL, &my_thread, NULL);
}

void end_thread()
{
    pthread_cancel(my_id);
}

如果我在我的机器上执行 ps aux,我会看到对于我的上述过程,RSS 部分总是在增加。但是如果我替换 pthread_cancel() 使用 pthread_join(),我的进程的 RSS 没有增加。

我没有在我的线程中分配任何资源,所以看起来 pthread_cancel() 没有在后台清理一些 pthread 相关的东西?

我知道 pthread_cancel() 正在杀死线程,因为我的线程数稳定在 2(通过 top ... main process + my_thread 检查)。

我查看了 pthread_cleanup_pop/push 函数,但它们看起来像是用于清理用户分配的内存。

我是否需要每次使用 pthread_cancel() 时都使用它们?

编辑:RSS 每循环一次增加 4kBytes。

最佳答案

在 pthread_cancel() 之后调用 pthread_detach() 将释放 pthread“自身”持有/使用的资源。

当然,用户必须自己确保在现在已取消的线程中他/她自己分配的资源也已释放。

关于在循环中调用 pthread_cancel() 显示内存使用量增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58118646/

相关文章:

C 编程数据结构用户输入无法初始化结构类型 Visual Studio

c++ - 为什么结构数组的大小在传递给函数时会发生变化?

linux - 为什么 linux sort 没有给我想要的结果?

php memory_get_usage(true) vs top %MEM

haskell - 如何避免堆栈空间溢出?

c - 如何扫描字符串并将其写入文件?

c - 如何获取文件的地址?

c++ - 如何制作终端提示信息?

linux - 在编译时链接与在运行时针对 std::library 链接

python - 如何防止 wxPython 子类中的内存泄漏?