How to destruct instance in atexit() - c++

I want to call destructor of an instance (proc) always before my program ends, especially after return 1 or exit() in main.
I found C++ function atexit(), but it requires pointer to void function with no argument, so the code below cannot be compiled. How I can solve it, please?
Destructor of my instance requires MySQL connection.
#include <WinSock.h>
#include <iostream>
#include <cstdio>
#include <stdio.h>
#include <mysql.h>
#include <string>
// Declarations for Mysql DB
using namespace std;
class Process {
public:
~Process();
};
Process::~Process ()
{
// Interaction with DB
}
int main(void)
{
// Join to DB
atexit(proc.~Process); // Call desctructor of instance proc before program ends
Process proc;
// App code
return 0;
}

proc has automatic duration, i.e. when exiting main, it will be destroyed automatically (and the destructor invoked) - you don't need the atexit business..
Unless as #Rob mentions below, you call exit() in your code somewhere... if that's the case, then you'll have to allocate Process on the heap, provide a function that atexit can call which is aware of this instance, and delete it there...

Just make it a global std::auto_ptr<> or std::unique_ptr<>:
std::auto_ptr<Process> proc; // 1) initialized with NULL before main() is called
int main() {
proc.reset(new Process); // 2) re-initialized
}
// 3) proc destructor is called after main() exits

Use C++:
#include <memory>
std::unique_ptr<Process> g_proc;
int main()
{
g_proc.reset(new Process(some, runtime, params));
// all done!
}
Objects of static storage duration (e.g. globals, like our g_proc here) are destroyed after main exits, and the destructor of unique_ptr will take care of the object destruction.
Alternatively you can make g_proc a static variable inside main, though that's a bit unusual.

Change your program logic slightly to allocate your Process object dynamically:
Process *pProc;
void killProc() {
delete pProc;
}
int main(void)
{
// Join to DB
atexit(killProc); // Call desctructor of instance proc before program ends
pProc = new Process();
Process& proc = *pProc;
// App code
return 0;
}

As proc is not a pointer, it will be automatically deleted at the end of the main() function, and it's destructor will be called (before the memory is deallocated).
The atexit() function is not a C++ function, but is part of the standard C library.
If you need to call the destructor BEFORE the end of the main() function, you need to allocate the proc variable as a pointer.
You can also avoid the usage of global variables plus C functions by using an application class this way:
class Application
{
public:
Application() { proc = new Process(); /* other init code */ }
~Application() { delete proc; /* other clean-up code */ }
int run()
{
/* your application code goes here */
}
private:
Process *proc;
}
int main()
{
Application app;
int result = app.run();
/* Post clean-up code */
return result;
}
If you plan using C++11 can also rely on the 'unique_ptr' template. Avoid using 'auto_ptr' since it is deprecated.

Related

calling atexit function within a class constructor

I want to use std::atexit function within the class for cleanup on abnormal termination.
I am registering function handle within the class constructor but getting an error. (codetest.cpp:12:25: error: invalid use of non-static member function)
here is my simple code for understanding (other it is a big project where application exit on some fatal error but I need to cleanup some attribute of mu class)
#include <iostream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
class cleanUP
{
public:
cleanUP ()
{
atexit (atexit_handler);
}
~cleanUP()
{
}
void atexit_handler ()
{
// Will cleanup some temp files and malloc things.
cout << "Call atexit" <<endl;
}
};
int main () {
cleanUP cleanup;
}
is there any other good approach for cleanup.
Thanks.
Your problem is that std::atexit can only register a true (unbound) function or a static method from a class but not a non static method.
If you do not need a pointer to the object, the simplest way would be to make the handler static:
static void atexit_handler ()
{
// Will cleanup some temp files and malloc things.
cout << "Call atexit" <<endl;
}
But anyway, if you create more than one object, you will register many times the same handler which is at least useless. If you really want (or need) to go that way you should:
ensure you register the handler only once by using a static guard variable (and a mutex or other critical section if you want to be thread-safe)
register the objects that need processing in a standard container that would be a static member of the class
make the static handler process the registered objects
But the idiomatic way of cleanup is simply to use a destructor and to ensure that all dynamic objects are correctly deleted before the program exits.

Prevent destruction of self after main?

I'm writing some asynchronous I/O stuff in C++, and I need to prevent an object from being destructed until its handler for the asynchronous I/O is called. I'm trying to use shared_ptr and create my object with a static constructor so I can be sure that it is using reference counting. Then I save that in a weak_ptr until I start the asynchronous I/O, when I store it into another shared_ptr to be sure it doesn't become invalid during that time. Finally, I reset it when the callback completes. Here's an example:
#pragma once
#include <memory>
#include <functional>
using namespace std;
class SomeIO {
std::weak_ptr<SomeIO> self;
std::shared_ptr<SomeIO> savingSelf;
void myCallback() {
// do my callback stuff here
savingSelf.reset();
}
public:
SomeIO() = delete;
~SomeIO() {}
static shared_ptr<SomeIO> create() {
auto self = make_shared<SomeIO>();
self->self = self;
return self;
}
void start() {
savingSelf = self.lock();
//startSomeAsyncIO(bind(self, SomeIO::myCallback));
}
};
int main() {
auto myIO = SomeIO::create();
myIO->start();
return 0;
}
My question is, what is going to happen after main returns? Will it stay alive until the final reference is released, or is this going to cause a memory leak? If this does cause a memory leak, how do I handle this situation so the asynchronous I/O can be canceled and the program can end without a memory leak? I would think that shared_ptr protects me from memory leaks, but I'm not so sure about this situation.
Thanks!
In C++ (as opposed to Java) , the program ends whenever the main ends. all other threads are terminated. memory leaks are not your problem since the program ends anyway and all the memory is deallocated.
you can use std::thread with std::thread::join to prevent you program from exiting too early :
int main (void){
std::thread myAsyncIOThread ([]{
auto myIO = SomeIO::create();
myIO->start();
});
//other things you program needs to do
myAsyncIOThread.join();
return 0;
}
you might want to be interested having a Thread-Pool in your program.

pthread_key_create destructor not getting called

As per pthread_key_create man page we can associate a destructor to be called at thread shut down. My problem is that the destructor function I have registered is not being called. Gist of my code is as follows.
static pthread_key_t key;
static pthread_once_t tls_init_flag = PTHREAD_ONCE_INIT;
void destructor(void *t) {
// thread local data structure clean up code here, which is not getting called
}
void create_key() {
pthread_key_create(&key, destructor);
}
// This will be called from every thread
void set_thread_specific() {
ts = new ts_stack; // Thread local data structure
pthread_once(&tls_init_flag, create_key);
pthread_setspecific(key, ts);
}
Any idea what might prevent this destructor being called? I am also using atexit() at moment to do some cleanup in the main thread. Is there any chance that is interfering with destructor function being called? I tried removing that as well. Still didn't work though. Also I am not clear if I should handle the main thread as a separate case with atexit. (It's a must to use atexit by the way, since I need to do some application specific cleanup at application exit)
This is by design.
The main thread exits (by returning or calling exit()), and that doesn't use pthread_exit(). POSIX documents pthread_exit calling the thread-specific destructors.
You could add pthread_exit() at the end of main. Alternatively, you can use atexit to do your destruction. In that case, it would be clean to set the thread-specific value to NULL so in case the pthread_exit was invoked, the destruction wouldn't happen twice for that key.
UPDATE Actually, I've solved my immediate worries by simply adding this to my global unit test setup function:
::atexit([] { ::pthread_exit(0); });
So, in context of my global fixture class MyConfig:
struct MyConfig {
MyConfig() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
::atexit([] { ::pthread_exit(0); });
}
~MyConfig() { google::protobuf::ShutdownProtobufLibrary(); }
};
Some of the references used:
http://www.resolvinghere.com/sof/6357154.shtml
https://sourceware.org/ml/pthreads-win32/2008/msg00007.html
http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_key_create.html
http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_exit.html
PS. Of course c++11 introduced <thread> so you have better and more portable primitves to work with.
It's already in sehe's answer, just to present the key points in a compact way:
pthread_key_create() destructor calls are triggered by a call to pthread_exit().
If the start routine of a thread returns, the behaviour is as if pthread_exit() was called (i. e., destructor calls are triggered).
However, if main() returns, the behaviour is as if exit() was called — no destructor calls are triggered.
This is explained in http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_create.html. See also C++17 6.6.1p5 or C11 5.1.2.2.3p1.
I wrote a quick test and the only thing I changed was moving the create_key call of yours outside of the set_thread_specific.
That is, I called it within the main thread.
I then saw my destroy get called when the thread routine exited.
I call destructor() manually at the end of main():
void * ThreadData = NULL;
if ((ThreadData = pthread_getspecific(key)) != NULL)
destructor(ThreadData);
Of course key should be properly initialized earlier in main() code.
PS. Calling Pthread_Exit() at the end to main() seems to hang entire application...
Your initial thought of handling the main thread as a separate case with atexit worked best for me.
Be ware that pthread_exit(0) overwrites the exit value of the process. For example, the following program will exit with status of zero even though main() returns with number three:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
class ts_stack {
public:
ts_stack () {
printf ("init\n");
}
~ts_stack () {
printf ("done\n");
}
};
static void cleanup (void);
static pthread_key_t key;
static pthread_once_t tls_init_flag = PTHREAD_ONCE_INIT;
void destructor(void *t) {
// thread local data structure clean up code here, which is not getting called
delete (ts_stack*) t;
}
void create_key() {
pthread_key_create(&key, destructor);
atexit(cleanup);
}
// This will be called from every thread
void set_thread_specific() {
ts_stack *ts = new ts_stack (); // Thread local data structure
pthread_once(&tls_init_flag, create_key);
pthread_setspecific(key, ts);
}
static void cleanup (void) {
pthread_exit(0); // <-- Calls destructor but sets exit status to zero as a side effect!
}
int main (int argc, char *argv[]) {
set_thread_specific();
return 3; // Attempt to exit with status of 3
}
I had similar issue as yours: pthread_setspecific sets a key, but the destructor never gets called. To fix it we simply switched to thread_local in C++. You could also do something like if that change is too complicated:
For example, assume you have some class ThreadData that you want some action to be done on when the thread finishes execution. You define the destructor something on these lines:
void destroy_my_data(ThreadlData* t) {
delete t;
}
When your thread starts, you allocate memory for ThreadData* instance and assign a destructor to it like this:
ThreadData* my_data = new ThreadData;
thread_local ThreadLocalDestructor<ThreadData> tld;
tld.SetDestructorData(my_data, destroy_my_data);
pthread_setspecific(key, my_data)
Notice that ThreadLocalDestructor is defined as thread_local. We rely on C++11 mechanism that when the thread exits, the destructor of ThreadLocalDestructor will be automatically called, and ~ThreadLocalDestructor is implemented to call function destroy_my_data.
Here is the implementation of ThreadLocalDestructor:
template <typename T>
class ThreadLocalDestructor
{
public:
ThreadLocalDestructor() : m_destr_func(nullptr), m_destr_data(nullptr)
{
}
~ThreadLocalDestructor()
{
if (m_destr_func) {
m_destr_func(m_destr_data);
}
}
void SetDestructorData(void (*destr_func)(T*), T* destr_data)
{
m_destr_data = destr_data;
m_destr_func = destr_func;
}
private:
void (*m_destr_func)(T*);
T* m_destr_data;
};

Stop execution without skipping destructors

Is it possible to terminate software execution without skipping calls to destructors? For instance, in the code below, the destructor for test will never be called because of the exit(1) statement.
#include <iostream>
#include <cstdlib>
using namespace std;
class A{
public:
A(){cout << "Constructed.\n";}
~A(){cout << "Destroyed.\n";}
};
void func()
{
//Assuming something went wrong:
exit(1);
}
int main(int argc, char *argv[])
{
A test;
func();
return 0;
}
What I need, is a way to end the program (from within func()) that calls all necessary destructors before terminating. So far I've been handling this through func() return value, as in:
bool func()
{
//Assuming something went wrong:
return false;
}
int main(int argc, char *argv[])
{
A test;
if( !func() )return 1;
return 0;
}
The problem with this method is that it quickly becomes very annoying (and code bloating) to manage once you need to apply it to a series of nested functions.
Is there a way of achieving the same results of the second example (proper destructor calls) with a syntax similar to the first example (call exit(1) wherever you are)?
Throw an exception, catch it in main and return.
This relies on nothing else catching your exception without rethrowing it.
You could rely on stack unwinding for this: when you want to exit, throw an exception and catch it in main().
struct my_exit
{
int error;
int operator()()
{
// do any cleanup on globals
return error;
}
};
int main()
{
try
{
doSomethingThatCouldCauseExit();
}
catch (my_exit & me)
{
// Clean up globals now
exit(me());
}
}
There are several ways to do this cleanly.
One solution is to use the atexit function, which simply calls the given function pointer when the program terminates.
You would have to allocate all of your objects off the heap, maintain some global table with pointers to all instantiated class instances, and then simply iterate through the table delete ing each instance in the registered function.

Can the signal system call be used with C++ static members of the class?

Is the following supported across *nix platforms?
#include <cstdio>
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>
class SignalProcessor
{
public:
static void OnMySignal(int sig_num)
{
printf("Caught %d signal\n", sig_num);
fflush(stdout);
return;
}
};
using namespace std;
int main()
{
signal(SIGINT,SingalProcessor::OnMySignal);
printf("Ouch\n");
pause();
return 0;
}
Technically no you can't.
You just happen to be getting lucky that your compiler is using the same calling convention that it uses for 'C' functions. As the C++ ABI is not defined the next version of the compiler is free to use a completely different calling convention and this will mess with your code with no warning from the compiler.
See: http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.2
See the note at the end of this section
Note: static member functions do not require an actual object to be invoked,
so pointers-to-static-member-functions are usually type-compatible with regular
pointers-to-functions. However, although it probably works on most compilers,
it actually would have to be an extern "C" non-member function to be correct,
since "C linkage" doesn't only cover things like name mangling, but also
calling conventions, which might be different between C and C++.
Edit:
To answer the comment by Sasha:
Using threading as an example:
#include <iostream>
class Thread
{ public: virtual void run() = 0; };
extern "C" void* startThrerad(void* data)
{
Thread* thread = reinterpret_cast<Thread*>(data);
try
{
thread->run();
}
catch(...)
{ /* Log if required. Don't let thread exit with exception. */ }
return NULL;
}
class MyJob: public Thread
{
public: virtual void run() {std::cout << "HI\n";}
};
int main()
{
MyJob job; // MyJob inherits from Thread
pthread_t th;
// In most situation you do not need to dynamic cast.
// But if you use multiple inheritance then things may get
// interesting, as such best to always use it.
pthread_create(&th,NULL,startThrerad,dynamic_cast<Thread*>(&job));
void* result;
pthread_join(th,&result);
}
That should work just fine. In fact, you could expand that function to call specific instances of that class dependent on the signal caught. For example, if you add a non-static method Process to you class, you can do something like this:
SignalProcessor* sp[MAX_SIGNALS];
static void SignalProcessor::OnMySignal(int sig_num)
{
printf("Caught %d signal\n", sig_num);
if (0 < sp[sig_num])
sp[sig_num]->Process();
fflush(stdout);
return;
}
I do the equivalent with Windows thead procedures and other assorted callbacks, and RTX interrupts all the time. The only real gotchas are that the members have to be static (which you already figured out), and that you have to make sure your routine is set to use the standard C/system call calling convention. Sadly, how you do that is platform dependent. In Win32 it is with the "__stdcall" modifier.
Note that you can use the passback-in pointer paramteter to "convert" such calls into normal class method calls. Like so ("self_calling_callback" is the static method):
unsigned long __stdcall basic_thread::self_calling_callback (void *parameter) {
if (parameter) {
basic_thread * thread = reinterpret_cast<basic_thread *>(parameter);
thread->action_callback();
}
return 0;
// The value returned only matters if someone starts calling GetExitCodeThread
// to retrieve it.
}
basic_thread::basic_thread () {
// Start thread.
m_Handle = CreateThread(NULL,
0,
self_calling_callback,
(PVOID)this,
0,
&m_ThreadId );
if( !IsHandleValid() )
throw StartException("CreateThread() failed", GetLastError());
}