#pragma once
#include <iostream>
#include <thread>
#include <vector>
#include <memory>
#include <future>
using std::cout;
using std::endl;
class Test_threadLocal
{
typedef Test_threadLocal self_type;
class ThreadLocalData
{
public:
ThreadLocalData()
{
cout << __FUNCTION__ << " threadId:" << std::this_thread::get_id() << endl;
}
~ThreadLocalData()
{
cout << __FUNCTION__ << " threadId:" << std::this_thread::get_id() << endl;
}
};
private:
bool entry()
{
thread_local ThreadLocalData data;
return true;
}
void runWithThread()
{
cout << __FUNCTION__ << " threadId:" << std::this_thread::get_id() << " begin ******************************" << endl;
std::vector<std::shared_ptr<std::thread>> threadGroup;
const int threadCount = 5;
for (int i = 0; i < threadCount; ++i)
{
std::shared_ptr<std::thread> t(new std::thread(&self_type::entry,this));
threadGroup.push_back(t);
}
for (int i = 0; i < threadCount; ++i)
{
threadGroup[i]->join();
}
cout << __FUNCTION__ << " threadId:" << std::this_thread::get_id() << " end ******************************" << endl;
int a = 5;
++a;
}
void runWithFuture()
{
cout << __FUNCTION__ << " threadId:" << std::this_thread::get_id() << " begin ******************************" << endl;
std::vector< std::future<bool> > futureList;
const int threadCount = 5;
for (int i = 0; i < threadCount; ++i)
{
futureList.push_back(std::async(std::launch::async, &self_type::entry, this));
}
bool bSuccess = true;
for (auto& f : futureList)
{
bool rtn = f.get();
cout << "rtn:" << rtn << endl;
}
cout << __FUNCTION__ << " threadId:" << std::this_thread::get_id() << " end ******************************" << endl;
int a = 5;
++a;
}
public:
static void test()
{
self_type obj;
obj.runWithThread();
obj.runWithFuture();
}
};
发现: runWithThread执行完毕后,正常调用 ThreadLocalData 析构函数
runWithFuture执行完毕后,并未调用 ThreadLocalData 析构函数 (这是个问题)