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

时间:2016-08-05 16:21:59

标签: c pthreads free

我在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 *)?

1 个答案:

答案 0 :(得分:2)

  

但是pthread_t不是一个可以包含一些内部指针的结构   应该被释放?

您不必担心pthread_t结构包含的内容(或者甚至是struct)或者它是如何实现的。您(可以)free()使用malloc()calloc() 分配的

  

也许有一些函数pthread_destroy(pthread_t *)?

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

所以,除非你以后需要线程ID用于任何目的(加入,使用pthread_kill()发送信号等),你做的很好。否则,您需要确保在代码中的适当位置(即不再需要线程ID时)free()。​​

我不完全确定你在代码中的分配方式。这是一个动态分配线程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已为10 pthread_t分配了一个块。基本上,每拨打free()(或malloc()calloc()),您就会拨打realloc()一次,而您传递给free()的指针必须是相同的以前由其中一个*alloc()函数返回。