Can I let an instance of pthread_t go out of scope?

I am programming C and pthreads. I have a long function that I want to run in a separate 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 exiting the start_long_running_function () function, the local variable 'thread' goes out of scope. This is normal - or I can risk problems, for example. when is the long_running_function () function completed?

I tried the approach illustrated in my code and it seems to work - but maybe this is just luck?

Regards, Joakim

+4
source share
2 answers

Yes - it is safe if the variable is beyond the scope. But remember that you must at one time do one of two things:

1) pthread_detach (), so the kernel will release some material related to it.

2) pthread_join (), which has as a side effect separating it.

If you do not, I think it will be a drain of resources.

+4
source

This is a C structure, ordinary old data, so there is no destructor to introduce side effects when it goes beyond. The only consequence of losing the area is that you can no longer see it.

I know your question is C, but many 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 similar with C, arg is a pointer to a malloc ed structure that contains a stream handle; frees stream frees upon completion.

0
source

All Articles