Question

I'm trying to create a detached thread so I won't need to free the memory allocated for it. Valgrind is used to check for memory leaks. I've used IBM example and written:

void *threadfunc(void *parm)
{
  printf("Inside secondary thread\n");
  return NULL;
}

int main(int argc, char **argv)
{
  pthread_t             thread;
  int                   rc=0;
  rc = pthread_create(&thread, NULL, threadfunc, NULL);
  sleep(1);
  rc = pthread_detach(thread);
  return 0;
}

this works and doesn't create leaks, but a version without "sleep(1);" doesn't. Why is this sleep(1) needed?

Was it helpful?

Solution

I'm trying to create a detached thread so I won't need to free the memory allocated for it.

In this case, pthread_detach() is not be required and hence should not be used. Additionaly, in this code snippet you have not done any explict memory allocation, so you should not worry about the freeing the memory.

Why is this sleep(1) needed?

When you create the new thread, parent and child threads can starts executing in any order. Its depends on the OS schedular and other factors. Now in this case if parent threads gets scheduled first then it is possible that its goes and exit the program before child thread starts execution.

By adding sleep in the parent context, the child thread is getting time to start and finish the execution before finished. But this is not good idea and as we do not know how much time child thread will take. hence pthread_jon() should be used in the parent context. For detailed information please refer to POSIX thread documentation and great arcicle from below link

https://computing.llnl.gov/tutorials/pthreads/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top