本文介绍了该进程是否在退出时自动清理pthread占用的资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的代码:

void *my_thread(void *data)
{
    while (1) { }
}

void foo_init(struct my_resource *res)
{
    pthread_create(&res->tid, NULL, my_thread, res);

    /* Some init code */
}

void foo_exit(void)
{
    /* Some exit code */
}

这种情况是这样的.初始化进程后,将使用指向我分配的资源的指针调用函数 foo_init()(分配由其他函数自动完成,这不在我的控制之下).在该函数中,我正在创建一个 pthread ,它可以无限循环地运行.

The scenario is something like this. When the process gets initialized, the function foo_init() is called with a pointer to my allocated resources(the allocation is done automatically by some other function, which isn't under my control). Within the function I am creating a pthread, which runs in infinite loop.

一段时间后,进程将终止,将调用函数 foo_exit(),但是这次没有指向我的资源的指针,因此我无法调用 pthread_join(),因为我的 tid 包含在 my_resource 结构中.

After a while when the process is about to terminate, the function foo_exit() is called, but this time without the pointer to my resources, and hence I am unable to call pthread_join(), as my tid is contained within my_resource structure.

现在我的问题是,与 pthreads 相关的资源是否在操作系统终止进程后被销毁?如果是,我如何确定.

Now my question is that, whether the resources pertaining to the pthreads are destroyed upon the termination of the process by the OS or not? If yes, how can I make that sure.

在不调用 pthread_join()的情况下终止进程是否安全?

Also is it safe to terminate the process without calling pthread_join()?

谢谢.

推荐答案

如果您在谈论分配的内存,可以.当某个进程退出时,分配给该进程的所有虚拟内存页面都将返回到系统,这将清除您在该进程中分配的所有内存.

If you're talking about allocated memory, yes. When a process exits all virtual memory pages allocated to that process are returned to the system, which will clean up all memory allocated within your process.

通常,操作系统应该清理与退出时的进程相关的所有资源.它将处理关闭文件句柄(可能包括套接字和RPC机制),擦除堆栈并清理该任务的内核资源.

Generally the OS is supposed to clean up all resources associated with a process on exit. It will handle closing file handles (which can include sockets and RPC mechanisms), wiping away the stack, and cleaning up kernel resources for the task.

简短的回答,如果操作系统在执行某个过程后仍无法清理,则说明它是操作系统中的错误.但是我们没有人编写越野车软件吗?

Short answer, if the OS doesn't clean up after a process it is a bug in the OS. But none of us write buggy software right?

这篇关于该进程是否在退出时自动清理pthread占用的资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 16:10