reusing pthread_t variable for currently running threads

Viewed 8353

I'm abit uncertain if the following code will lead to undefined behavior.

//global
pthread_t thread1;

void *worker(void *arg){
  //do stuff
}


void spawnThread(){
  //init stuff
  int iret1 = pthread_create( &thread1, NULL, worker, (void*) p);
}

My spawnThread will make a new thread using the global thread1.

If I'm currently running a thread that is not finished, will I somehow cause undefined behaviour when starting a new thread using the thread1 variable?

If this is a problem, would it make sense to make my pthread_t variable local to a function? I think it might be problem because it will use the stack, and as soon as i return from my function that will be removed.

If I make my pthread_t local to a function, I can't use the pthread_join in a another part of my program. Is the canonical solution, to have a mutex'ed counter keeping track of how many current threads are running?

thanks

3 Answers
Related