簡體   English   中英

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演示了內存,未檢測到內存泄漏。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM