How do I safely delete static C++ objects in the case when multiple (Posix) threads call exit() in parallel?
It appears in my CentOS6 environment that exit() executes atexit (or on_exit) cleanup handlers by calling something like fct[--cnt]() where cnt is the number of handlers registered. When multiple threads call exit() at the same time, we have a race condition in the unprotected --cnt operation and some handlers may be skipped or called multiple times (leading to the occasional crash).
So how can I ensure that just one of the exit() calling threads does the cleanup and all others stop? Note that inserting a pthread_mutex_lock() into a cleanup handler doesn't help because this handler might be skipped...
Unfortunately I can't avoid that multiple threads call exit() because that's code my users will write (I'm providing a library to them).
Looking for safe ideas, thanks!
exit(), usemy_safe_exit()", and then refer to that when customers complain that it doesn't work.stream::flush(), but don't actively close it in the destructor?#define exit() my_safe_exit()in some suitable place(s).