创建两个类:
- CThreadGroup:启动多个线程并等待它们完成(使用连接)。
- CMainThread:启动一系列此类(CThreadGroup)并等待它们完成(使用连接)。将要启动的 CThreadGroup 数量和 CThreadGroup 启动的子线程数作为 inout 参数
在 main 中声明一个 CMainThread 类型的对象。
这是类的原型:
主线程
#include "ThreadGroup.h"
#include <mutex>
class CMainThread
{
std::vector<CThreadGroup> vThreadGroups;
std::vector<std::thread> vThreads;
const unsigned int nbMainThreads;
const unsigned int nbSubthreads;
public:
CMainThread(unsigned int nbMainThreads,
unsigned int nbSubthreads);
~CMainThread(void);
};
#include <thread>
#include <vector>
class CThreadGroup
{
const unsigned int nbThreads;
public:
CThreadGroup(unsigned int nbThreads);
~CThreadGroup(void);
};
线程组
#include <thread>
#include <vector>
class CThreadGroup
{
const unsigned int nbThreads;
public:
CThreadGroup(unsigned int nbThreads);
~CThreadGroup(void);
};
这是cpp文件
CMainThread::CMainThread(unsigned int nbMainThreads_,
unsigned int nbSubthreads_):
nbMainThreads(nbMainThreads_),
nbSubthreads(nbSubthreads_)
{
std::mutex mut;
for (unsigned int i=0;i<nbMainThreads;++i)
{
vThreads.push_back(std::thread([&]{
CThreadGroup currThread(nbSubthreads);
std::lock_guard<std::mutex> lock(mut);
vThreadGroups.push_back(currThread);
}));
}
for (auto it=vThreads.begin(); it!=vThreads.end(); ++it)
{
it->join();
}
}
线程组
CThreadGroup::CThreadGroup(unsigned int nbThreads_):
nbThreads(nbThreads_)
{
std::vector<std::thread> vThreads;
for (unsigned int i=0;i<nbThreads;++i)
{
vThreads.push_back(std::thread([i]{std::this_thread::sleep_for(std::chrono::seconds(i));}));
}
for (auto it=vThreads.begin(); it!=vThreads.end(); ++it)
{
it->join();
}
}
希望有帮助,