使用容器管理多个类对象,通过函数启动容器中所有类对象的函数。
#include <iostream>
#include <thread>
#include <vector>
#include <chrono>
#include <memory>
class Apple {
public:
Apple(int num):workspaceNum(num) {}
void start() {
flag = true;
while (flag && count < 10) {
std::cout << "这是线程: " << workspaceNum << std::endl;
std::chrono::milliseconds sleeptime(1000);
std::this_thread::sleep_for(sleeptime);
count++;
}
}
void end()
{
flag = false;
}
private:
int workspaceNum;
bool flag = false;
int count = 0;
};
class Menu {
public:
void addApple(Apple& apple)
{
appleVec.push_back(apple);
}
void startThread() {
for (int i = 0; i< appleVec.size() ; i++)
{
auto threadPtr = std::make_shared<std::thread>([this,i]() {
appleVec[i].start();
});
//智能指针插入到容器中。
threads.push_back(threadPtr);
}
}
void joinAllThreads()
{
for (auto& threadPtr : threads)
{
if (threadPtr->joinable())
{
threadPtr->join();
}
}
}
private:
std::vector<Apple> appleVec;
std::vector<std::shared_ptr<std::thread>> threads;
};
int main()
{
Apple apple1(1);
Apple apple2(2);
Menu menu;
menu.addApple(apple1);
menu.addApple(apple2);
menu.startThread();
menu.joinAllThreads();
return 0;
}