64,645
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <thread>
#include <list>
using namespace std;
class CTest
{
public:
CTest(){printf("%s [%p]\r\n","构造函数",(void*)this);}
~CTest(){printf("%s [%p]\r\n","析构函数",(void*)this);}
void Printf(char *sMsg){printf("%s [%p]\r\n",sMsg,(void*)this);}
};
std::list<CTest*>g_TestList;
void ThreadPro()
{
int nCount = 5;
while (nCount--)
{
if (g_TestList.size())
{
CTest *pTest = g_TestList.front();
g_TestList.pop_front();
pTest->Printf("ThreadPro test1");
delete pTest;
pTest->Printf("ThreadPro test2");
pTest = nullptr;
}
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
}
int main()
{
CTest *pTest = new CTest;
printf("%s [%p]\r\n","main test1",&pTest);
g_TestList.push_back(pTest);
std::thread th = std::thread(ThreadPro);
th.join();
pTest->Printf("main test2");
printf("%s [%p]\r\n","main test3",&pTest);
}
#include <iostream>
#include <thread>
#include <list>
using namespace std;
class CTest
{
public:
CTest(){printf("%s [%p]\r\n","构造函数",(void*)this);}
~CTest(){printf("%s [%p]\r\n","析构函数",(void*)this);}
void Printf(char *sMsg){printf("%s [%p]\r\n",sMsg,(void*)this);}
};
void ThreadPro(CTest *pTest)
{
int nCount = 5;
while (nCount--)
{
pTest->Printf("ThreadPro test");
}
delete pTest;
}
int main()
{
CTest *pTest = new CTest;
std::thread *pth = new std::thread(ThreadPro,pTest);
pth->join();
delete pth;
pTest->Printf("main test2");
printf("%s [%p]\r\n","main test3",&pTest);
}