Search code examples
pthreadspthread-join

Is it necessary to free the memory malloced for Pthreads?


The code is as follows:

    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?

So, is it necessary to free(threads)? Does the pthread_attr_destroy(&pta) free the memory resources?


Solution

  • After a little searching, I think that's needed.

    pthread_attr_destroy does destroy pthread_attr_t which was made by pthread_attr_init. That's all.

    And if pthread_attr_destroy really does free the memory, how about this example?

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