創建兩個類:
- CThreadGroup:啓動一個線程數和等待他們(使用連接)完成。
- CMainThread:啓動一系列此類(CThreadGroup)並等待它們完成(使用連接)。作爲inout參數啓動CThreadGroup的數量以及啓動多少個子線程CThreadGroup
在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();
}
}
希望幫助,
哪些線程在做什麼?他們是否得到自己的一塊數據來處理數據,還是共享數據? –
子任務在給定組內是獨立的,並且這些組獨立於其他組。 –
爲了澄清,任務僅僅是一個需要執行的功能,所以我想我會對它們進行排隊。該隊列必須是線程安全的,我必須弄清楚如何確定屬於某個組的所有任務何時完成,以及何時完成所有組。 –