tags:

views:

152

answers:

1

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.

+3  A: 

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);
}
Matt Joiner
@Anacrolix: Thanks! I feel so dumb: I should have checked the header file (`typedef unsigned long int pthread_t;`).
jldupont
i just appreciate people asking real questions about decent platforms and languages :)
Matt Joiner
@jldupont: `pthread_t` can be a pointer or a structure as well.
Bastien Léonard