是否有必要释放为 Pthreads 分配的内存?

Is it necessary to free the memory malloced for Pthreads?

代码如下:

    pthread_t *threads;
    pthread_attr_t pta;

    threads = (pthread_t *) malloc(sizeof(pthread_t) * NumThreads);
    pthread_attr_init(&pta);
    for(i=0; i<NumThreads; i++) {
        pthread_create(&threads[i], &pta, (void*(*)(void*))Addup, (void*)(i+1));
    } 

    for(i=0; i<NumThreads; i++) {
        ret_count = pthread_join(threads[i], NULL); 
    }

    pthread_attr_destroy(&pta);

    free(threads); // Is this needed?

所以,有必要free(threads)吗? pthread_attr_destroy(&pta) 是否释放内存资源?

经过一番搜索,我认为需要

pthread_attr_destroy 确实破坏了 pthread_attr_init 制作的 pthread_attr_t。就这些了。

如果 pthread_attr_destroy 确实 free 内存,这个例子怎么样?

pthread_t thrd;
pthread_attr_t pta;

pthread_attr_init(&pta);
thrd = pthread_create(...);
...
pthread_attr_destroy(&pta); // What memory should he free?

很简单:每次调用 malloc() 只需要调用一次 free() 就不会泄漏内存。

free(threads); // Is this needed?

所以是的,绝对需要它!

这与PThread完全无关-API.