atexit and thread-specific-storage

  • Follow


Hi folks,

I've just been thinking about thread-specific storage, with the idea
of writing some portable C++ wrapper functions, and have been
experimenting with the pthread TSS functions on Linux with the
following program. If I compile and run as-is, then it just prints
"atexit". If I uncomment the pthread_exit call, then it prints
"destructor 42" first. I would have expected "destructor 42" to have
been printed in either case. Am I wrong in my expectation, or is this
a bug in the implementation?

Thanks,

Anthony

#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>

void ae_func()
{
    printf("atexit\n");
}

void destructor_func(void* val)
{
    printf("destructor %i\n",(long)val);
}

pthread_key_t key;

int main()
{
    pthread_key_create(&key,destructor_func);
    pthread_setspecific(key,(void*)42);
    atexit(ae_func);
    /* pthread_exit(0); */
    return 0;
}

0
Reply anthony.ajw (46) 7/9/2007 7:48:06 PM

Returning from 'main' is equivalent to calling 'exit'. Calling 'exit'
terminates the process. The 'exit' function calls registered 'atexit'
functions, cleans up standard I/O, and calls '_exit'. The '_exit' is
guaranteed to terminate the process and can't really safely call any
user code (because that code could fail or deadlock).

Basically, it is your responsibility to clean up the state of any
threads before calling 'exit'. It almost has to be this way because
there is no safe, generic way to cleanup a thread. (Suppose it holds a
mutex that your destructor also needs to acquire.)

DS

0
Reply David 7/10/2007 9:04:14 AM


David Schwartz <davids@webmaster.com> writes:

> Returning from 'main' is equivalent to calling 'exit'. Calling 'exit'
> terminates the process. The 'exit' function calls registered 'atexit'
> functions, cleans up standard I/O, and calls '_exit'. The '_exit' is
> guaranteed to terminate the process and can't really safely call any
> user code (because that code could fail or deadlock).
>
> Basically, it is your responsibility to clean up the state of any
> threads before calling 'exit'. It almost has to be this way because
> there is no safe, generic way to cleanup a thread. (Suppose it holds a
> mutex that your destructor also needs to acquire.)

Thanks. It makes sense if you think about it, and it is documented behaviour.

It's just a bit strange that the TSS destructor functions are only run for the
main thread on pthread_exit, and not when the thread function (main) exits.

Anthony
-- 
Anthony Williams
Just Software Solutions Ltd - http://www.justsoftwaresolutions.co.uk
Registered in England, Company Number 5478976.
Registered Office: 15 Carrallack Mews, St Just, Cornwall, TR19 7UL
0
Reply Anthony 7/10/2007 4:10:01 PM

2 Replies
205 Views

(page loaded in 0.006 seconds)

4/28/2013 3:50:11 AM


Reply: