#ifndef _STUDY_PACKAGED_TASK_H_
#define _STUDY_PACKAGED_TASK_H_
#include <iostream>
#include <thread>
#include <future>
#include <string>
class CStudyPack
{
public:
CStudyPack(std::string strName, int32_t id) :m_strMyName(strName), m_iMyId(id) {}
int32_t Initialize(const std::string & strName);
std::string GetName() { return m_strMyName; }
private:
std::string m_strMyName;
int32_t m_iMyId;
};
class CStudyPackManager
{
public:
int32_t Initialize();
};
#endif
#include "study_packaged_task.h"
#include <list>
int32_t CStudyPack::Initialize(const std::string& strName)
{
int32_t iSize = std::atoi(strName.c_str());
return iSize;
}
//IntPackStruct XXXFunction()
//{
// IntPackStruct XXXValue;
// return XXXValue;
//}
int32_t CStudyPackManager::Initialize()
{
using IntPackStruct = std::pair<int32_t,CStudyPack*>;
std::list<std::pair<std::future<IntPackStruct>, std::thread>> listThread;
for (int i = 0;i <100;++i )
{
std::string strName = std::to_string(i);
CStudyPack* pStudy = new CStudyPack(strName,i);
// 也可以参考std::packaged_task<IntPackStruct()> pkgFunc{XXXFunction};
std::packaged_task<IntPackStruct()> pkgFunc([=]() {
return std::make_pair(pStudy->Initialize(strName), pStudy);
});
std::future<IntPackStruct> futureVal = pkgFunc.get_future();
listThread.emplace_back(std::move(futureVal), std::move(pkgFunc));
}
while (!listThread.empty())
{
auto& Item = listThread.front();
IntPackStruct resultValue = Item.first.get();
Item.second.join();
listThread.pop_front();
std::cout << "thes result is :" << resultValue.first << std::endl;
}
return 1;
}
int main(int argc, char *argv[])
{
std::unique_ptr<CStudyPackManager> pStudyPackManager = std::make_unique<CStudyPackManager>();
int iResult = pStudyPackManager->Initialize();
return iResult;
}
挺好用