C++:如何使用thread_local声明一个指针变量?
C++: How to use thread_local to declare a pointer variable?
我试图声明 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 以正确的方式声明指针变量?
谢谢。
标准对线程的支持非常基础。
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));
}
}
thread_local static std::unique_ptr<A> s_a;
有效。任务管理器中的内存不正确。我用vld来演示内存,没有检测到内存泄漏。
我试图声明 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 以正确的方式声明指针变量?
谢谢。
标准对线程的支持非常基础。
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));
}
}
thread_local static std::unique_ptr<A> s_a;
有效。任务管理器中的内存不正确。我用vld来演示内存,没有检测到内存泄漏。