Let's say I:
malloc
a pthread_t
for 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
.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With