mardi 26 septembre 2017

C++: How to use thead_local to declare a pointer variable?

I tried to declare thead_local pointer variable and then point to a new object in one thread.

thread_local static A* s_a = nullptr;

Seemed the memory of the new object was not released when the thread destroyed. I also tried to use unique_ptr, but still memory leak.

Here is the code. Add a break point at return 0, check the memory of the process, you will see the memory increases a lot.

#include "stdafx.h"

#include <iostream>
#include <thread>

class A
{
public:
    A(const std::string& name) : name_(name) { std::cout << (name_ + "::A").c_str() << std::endl; }
    ~A() { std::cout << (name_ + "::~A").c_str() << std::endl; }

    const std::string& name(){ return name_; }
private:
    std::string name_;
};

thread_local static std::unique_ptr<A> s_a;
//thread_local static A* s_a = nullptr;

static void test(const std::string& name)
{
    //A a(name);
    if(!s_a)
        s_a.reset(new A(name));
        //s_a = new A(name);
}

int main()
{
    for (size_t i = 0; i < 10000; i++)
    {
        {
            std::thread t0(test, "t0");
            std::thread t1(test, "t1");
            t0.join();
            t1.join();
        }
    }
    return 0;
}

My question is how to use thead_local to declare a pointer variable in correct way?

Thanks.

Aucun commentaire:

Enregistrer un commentaire