我正在用我的 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/