I am programming with C and pthreads. I have a long running function which I want to run in a seperate thread:
void long_running_function(void * arg) {
...
}
void start_long_running_function(void * arg) {
pthread_t thread;
pthread_create( &thread , NULL , long_running_function , arg);
/* What about the thread variable? */
}
When leaving the start_long_running_function() function the local variable ‘thread’ will go out of scope. Is this OK – or can I risk problems e.g. when the long_running_function() is complete?
I have tried the approach illustrated in my code, and it seems to work – but maybe that is only luck?
Regards Joakim
Yes — it’s safe to let the variable go out of scope. But remember you have to at some point do one of two things:
1) pthread_detach() it so the kernel will free some kind of stuff that’s associated with it.
2) pthread_join() it which has as a side-effect detaching it.
If you don’t, I think this will be a resource leak.