gpt4 book ai didi

c - 如何在 C 中正确释放 pthread_t 数组?

转载 作者:太空宇宙 更新时间:2023-11-04 08:11:51 27 4
gpt4 key购买 nike

我在 C 中有这样的 pthread_t 数组。

pthread_t *workers;         // worker threads running tasks from queue
workers = malloc(sizeof(pthread_t)*workers_count)

// then I creates pthread by passing &workers[i] to pthread_create()

现在我正在考虑如何释放它们。我做了这样的事情:

for(int i=0; i<workers_count; i++)
free(workers[i]);
free(workers);

但是 pthread_t 不是一个可以包含一些应该被释放的内部指针的结构吗?也许有一些函数 pthread_destroy(pthread_t *)?

最佳答案

But isn't pthread_t a struct that can contain some internal pointers that should be freed?

您不必担心pthread_t 结构包含什么(或者它是否甚至是一个struct)或它是如何实现的。您(只能)free() 使用 malloc()calloc() 等分配的内容。

Maybe there is some function pthread_destroy(pthread_t *)?

没有这样的功能,因为不需要这样的功能。

因此,除非您稍后出于任何目的(加入、使用pthread_kill() 发送信号等)需要线程 ID,否则您所做的都没有问题。否则,您需要确保在代码中的适当位置执行 free()(即不再需要线程 ID 时)。


我不完全确定你在代码中是如何分配的。下面是一个动态分配线程 ID 的简单示例,可能会稍微说明一下。

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

void* doSomeThing(void* arg)
{
printf("From thread function: Thread ID: %ld\n", (long)pthread_self());
return NULL;
}

int main(int argc, char *argv[])
{
size_t count = 10;
pthread_t *tid;

tid = malloc(count * sizeof *tid);

for(size_t i = 0; i< count; i++) {
int rc = pthread_create(&tid[i], NULL, &doSomeThing, NULL);
if(rc) { /* failure */ }
}

for(size_t i = 0;i<count; i++) {
pthread_join(tid[i], NULL);
}

free(tid);
return 0;
}

在上面的例子中,我加入线程。由于加入需要线程 ID,因此我在之后 free() tid

另外,您可以看到我只调用了一次 free(),因为 tid 被分配了一个 block 用于 10 个 pthread_t。基本上,每次调用 malloc()(或 calloc()realloc()) 并且您传递给 free() 的指针必须与之前由 *alloc() 之一返回的相同功能。

关于c - 如何在 C 中正确释放 pthread_t 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38793807/

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