Question

May it cause errors when I use pthread_create in the following way?

void myFunction(){
  thread_t myThread;
  pthread_create(&myThread,0,myRoutine,0);
}

I am not sure if the usage of the local variable myThread can cause errors because it ceases to exist when myFunction() exits.

Could the memory of myThread still be used in the kernel when the function exits?

I will not need the thread id stored in myThread so I don't want to allocate memory and free it again.

Was it helpful?

Solution 2

You can also pass PTHREAD_CREATE_DETACHED as part of thread attribute when you create it. This way, you dont have to worry about joining the thread later on. Something like this:

 pthread_t;
 int status;
 pthread_attr_t attr;

 status = pthread_attr_init(&attr);
 if (status != 0) {
     fprintf(stderr, "pthread_attr_init() failed [status: %d]\n", status);
     return 0;
 }

 status = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
 if (status != 0) {
     fprintf(stderr, "pthread_attr_setdetachstate() failed [status: %d]\n", status);
     return 0;
 }

 status = pthread_create(&t, &attr, myRoutine, 0);

OTHER TIPS

You shouldn't let a thread "just finish", as that can definitely cause problems. If you expect the thread to just finish on it's won, you should AT LEAST use pthread_detach, at which point the thread is completely "freestanding", and should be OK to just leave it be.

May it cause errors when I use pthread_create in the following way?

Yes: you now have no way to join the thread when it finishes. This is a resource leak, analogous to losing the only pointer to allocated memory.

If you really don't want to shut it down in a controlled way, then you could call pthread_detach to make it responsible for tidying up its own resources; then you can safely abandon the thread handle.

Could the memory of myThread still be used in the kernel when the function exits?

No. pthread_t is just a handle used to access a thread's resources. It doesn't manage those resources, and it doesn't need to exist unless you need to access them.

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