gpt4 book ai didi

c - 什么时候在 C 中释放动态分配的 pthread_t 指针?

转载 作者:太空宇宙 更新时间:2023-11-03 23:49:20 24 4
gpt4 key购买 nike

我有一个代码块,它输入一个 case 语句。如果我遇到正确的情况,我需要创建一个新线程并继续执行工作。可以多次调用此 case 语句,创建多个同时运行的线程。

因此,我想我需要创建一个 pthread_t*,为其分配一些内存,然后调用 pthread_create()。但是,我还需要释放 pthread_t* 吗?我不想造成内存泄漏。如果我需要释放它,我应该如何以及在哪里释放它?

例如:

case MY_CASE:
;
pthread_t* foo = (pthread_t*)malloc(sizeof(pthread_t));
pthread_create(foo, NULL, SomeFunction, &SomeParameters);
.
.
.
later
.
.
.
free(foo); // Should this be in the code? If so, where?
/* I need to ensure the main thread keeps running. So, I cannot use pthread_join() */

最佳答案

在调用 pthread_join(*foo, &retval); 后释放内存。

如果您想轮询所有线程以查看它们是否已完成,请保留一组打开的句柄并调用 pthread_tryjoin_np在他们。然后调用 free(并从数组中删除)您的指针以指示已终止的线程。

或者,您可以调用 pthread_detach在你的线程上。这更便携,如果您不关心您的线程是否已终止,它也能很好地工作。在这种情况下,pthread_detach 手册页是这样说的:

A new thread can be created in a detached state using pthread_attr_setdetachstate(3) to set the detached attribute of the attr argument of pthread_create(3)

而且您可以完全跳过 malloc

关于c - 什么时候在 C 中释放动态分配的 pthread_t 指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24686182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com