2017-09-26 87 views
0

我试图声明thread_local指针变量,然后指向一个线程中的新对象。C++:如何使用thread_local声明一个指针变量?

thread_local static A* s_a = nullptr; 

看到新对象的内存没有在线程销毁时被释放。我也尝试使用unique_ptr,但仍然存在内存泄漏。我使用VS 2015

这里是代码。在return 0处添加一个断点,检查进程的内存,你会看到内存增加很多。

#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; 
} 

我的问题是如何使用thread_local以正确的方式声明指针变量?

谢谢。

+0

我想它是在一个线程单一实例,是什么把它删除的时机?为什么使用unique_ptr还是内存泄漏? – ldlchina

+1

相关:https://stackoverflow.com/questions/17668729/memory-leak-in-gcc-4-8-1-when-using-thread-local。 [gcc错误报告](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57914)。应该在4.8.2中固定。 – AMA

+1

'static thread_local unique_ptr'应该可以工作。你怎么知道有泄漏? – rustyx

回答

0

thread_local static std::unique_ptr<A> s_a;作品。任务管理器中的内存不正确。我用vld来演示内存,没有检测到内存泄漏。

1

该标准对线程的支持是非常基本

Boost的跨平台的支持当然是出众:

// for thread_specific_ptr 
#include <boost/thread/tss.hpp> 


// define a deleter for As 
void destroy_a(A* ptr) noexcept 
{ 
    delete ptr; 
} 

// define the thread_specific pointer with a deleter 
boost::thread_specific_ptr<A> s_a { &destroy_a }; 


static void test(const std::string& name) 
{ 
    // create the object in a manner compatible with the deleter 
    if(!s_a.get()) 
    { 
     s_a.reset(new A(name)); 
    } 
} 
+0

谢谢,这可能工作,我没有尝试。但由于某些原因,我不能使用的推动作用。:( – ldlchina

+1

因此,许多人似乎在他们的工作中使用升压阻止。对我来说,这似乎是一条腿走路,这是一个耻辱。 –

+0

对。我同意提升是非常有用的。 – ldlchina