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

calling pthread_cancel() in loop shows increase MEM usage

我正在使用我的 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,我发现对于我的上述过程,如果我将 pthread_cancel() 替换为 [=16],RSS 部分始终是 increasing.But =],我的进程的 RSS 没有增加。

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

我知道 pthread_cancel() 正在终止线程,因为我的线程数稳定在 2(已检查 top ... 主进程 + my_thread)。

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

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

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

在 pthread_cancel() 之后调用 pthread_detach() 将释放 pthread 本身 held/used 的资源。

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