Tuesday, February 8, 2011

Will pthread_detach manage my memory for me?

Suppose I have the following code:

while(TRUE) {
  pthread_t *thread = (pthread_t *) malloc(sizeof(pthread_t));
  pthread_create(thread, NULL, someFunction, someArgument);
  pthread_detach(*thread);
  sleep(10);
}

Will the detached thread free the memory allocated by malloc, or is that something I now have to do?

  • No. pthread_create() has no way of knowing that the thread pointer passed to it was dynamically allocated. pthreads doesn't use this value internally; it simply returns the new thread id to the caller. You don't need to dynamically allocate that value; you can pass the address of a local variable instead:

    pthread_t thread;
    pthread_create(&thread, NULL, someFunction, someArgument);
    
  • You need to free the memory yourself. It would be preferable to simply allocate the pthread_t variable on the stack as opposed to the heap.

    From Andrew

0 comments:

Post a Comment