Reputation: 2031
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
Upvotes: 4
Views: 965
Reputation: 33385
It's a C structure, Plain Old Data, so there's no destructor to introduce side-effects when it goes out of scope. The only implication of losing scope is that you can't see it any more.
I know yours is a C question, but a lot of thread implementations solve the problem with something like this:
class Thread {
pthread_t handle;
static void * start (void * self) {
static_cast <Thread *> (self) -> run ();
}
protected: void run () = 0;
public: void start () {
pthread_create (&handle, NULL, start, this);
}
~ Thread () {
pthread_join (&handle, NULL);
}
};
You can do something analogous with C, the arg
is a pointer to a malloc
ed struct which contains the thread handle; the thread function frees
it on termination.
Upvotes: 0
Reputation: 39356
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.
Upvotes: 4