mardi 28 mars 2017

How to only disable destruction of objects in thread-local-storage?

#include <cstdlib>
#include <thread>
#include <chrono>

using namespace std;
using namespace std::literals;

struct A
{
    A() { cout << "A()" << endl; }    
    ~A() { cout << "~A()" << endl; }
};

A g_a;

int main()
{
    thread([]()
    {
        thread_local A a;
        this_thread::sleep_for(24h);
    }).detach();

    exit(0); // not ok
    quick_exit(0); // still not ok
}

  • Global objects and objects in thread-local-storage will be destructed after calling exit(0);
  • Global objects and objects in thread-local-storage will not be destructed after calling quick_exit(0);

Is it possible:

Global objects are destructed after calling some_exit_func(0); while objects in thread-local-storage are not destructed.

Problem background:

I have a big legacy project, which has used thread-local-storage to store many C++ objects; before C++11, these objects will not be destructed automatically, so the former writer explicitly calls their destructors.

Now, I want to recompile it with a C++11 compiler; I am faced with such a problem:

  • If I use exit(0), the objects in thread-local-storage will be double-destructed;
  • If I use quick_exit(0), the global variables will not be destructed.

Aucun commentaire:

Enregistrer un commentaire