dimanche 26 novembre 2017

Destruction of thread_local objects

In the question Using QSqlQuery from multiple threads there was the outcome that thread storage solves the problem.

I made a simple demo code to be absolutely clear about C++11 thread_local specifier. The code below creates two threads which have ThreadLocal object as a local unique object. The Storage::get function is a thread specific singleton. Does the standard guarantee that ThreadLocal destructor is called on join or the exit of the thread function?

Compiled with GCC 5.4.0 (g++ -o main main.cpp --std=c++11 -lpthread)

#include <thread>
#include <mutex>
#include <string>
#include <chrono>
#include <iostream>
#include <atomic>

static std::mutex mtx;

struct ThreadLocal {
    std::string name;

    ~ThreadLocal() {
        mtx.lock();
        std::cout << "destroy " << name << std::endl;
        mtx.unlock();
    }
};

struct Storage {
    static ThreadLocal &get() {
        /* Thread local singleton */
        static thread_local ThreadLocal l;
        static std::atomic<int> cnt(0);
        l.name = std::to_string(cnt);
        cnt++;
        return l;
    }
};

void thread() {
    mtx.lock();
    std::cout << Storage::get().name << std::endl;
    mtx.unlock();
    std::this_thread::sleep_for(std::chrono::seconds(1));
}

int main(int argc, const char **argv) {
    std::thread t1(&thread);
    std::thread t2(&thread);
    t1.join();
    t2.join();
}

Aucun commentaire:

Enregistrer un commentaire