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
The
pthread_tis just an identifier. You can copy it round or destroy it at will. Of course, as you mention, if you destroy it (because it is local) then you cannot use it to callpthread_join.If you reuse the same
pthread_tvariable for multiple threads then unless there is only one thread active at a time you are overwriting the older values with the new ones, and you will only be able to callpthread_joinon the most recently started thread. Also, if you are starting your threads from inside multiple threads then you will need to protect thepthread_tvariable with a mutex.If you need to wait for your thread to finish, give it its own
pthread_tvariable, and callpthread_joinat the point where you need to wait. If you do not need to wait for your thread to finish, callpthread_detach()after creation, or use the creation attributes to start the thread detached.