Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a pthread perform clean-up on its own?

Tags:

linux

pthreads

Let's say I:

  • malloc a pthread_tfor holding a thread context

  • pthread_create with as user parameter the pointer to the pthread_t structure

In other words, the thread function has access to its pthread_t context structure. Now here is the tricky bit:

How can the pthread exit on its own and get the pthread_t context freed somehow? i.e. is it possible not to involve the parent thread? (no mutex/join etc.)

Think of this as a "lightweight process".

(and no the thread cannot free() the structure just before exiting its thread_func.

like image 506
jldupont Avatar asked Feb 03 '23 08:02

jldupont


1 Answers

The pthread_t you receive when creating a thread is merely its ID, used to refer to that thread from other threads.

To have the thread context freed automatically when the thread terminates, you should detach it from the parent thread using pthread_detach()

If you pass a pointer to the pthread_t returned from the initial pthread_create(), you could simply free() it immediately in the new thread's start routine. If you need to refer to the pthread_t value for the current thread again, just call pthread_self(). However it would be much easier to allocate pthread_t on the stack in the parent thread, and not bother to pass it to the child thread at all (or rather pass something more useful).

void *child_routine(void *arg)
{
    pthread_t thread = pthread_self();
}

void parent()
{
    pthread_t thread;
    pthread_create(&thread, NULL, child_routine, NULL);
    pthread_detach(thread);
}
like image 155
Matt Joiner Avatar answered Feb 06 '23 14:02

Matt Joiner