【发布时间】:2021-01-06 08:32:40
【问题描述】:
我有一个名为 Executor 的类,其中一个 vector
这是我的 Executor.h 代码:
#include <thread>
#include <mutex>
#include <iostream>
#include <vector>
#include <functional>
using namespace std;
class Executor
{
protected:
vector<thread*> threads;
mutex m;
public:
void submit(const std::function<void()>& f);
Executor();
~Executor();
};
Executor.cpp:
#include "Executor.h"
void Executor::submit(const std::function<void()>& f)
{
{
lock_guard<mutex> lock(m);
thread t(f);
threads.push_back(&t);
}
}
Executor::Executor() {}
Executor::~Executor()
{
for (unsigned int i = 0; i < threads.size(); i++)
{
threads.at(i)->join();
delete threads.at(i);
}
threads.clear();
}
还有main():
Executor ex;
auto fact = [](){cout<< "factor(55) = " << factor(55); };
auto pk = [](){cout << "P2(100, 50) = " << P2(100, 50); };
auto fib = [](){cout << "fibonacci(45) = " << fibonacci(45); };
ex.submit(fact);
ex.submit(pk);
ex.submit(fib);
【问题讨论】:
-
不能存储指向局部变量的指针
-
为什么会有一个指向线程的指针向量?这没有任何意义。自己创建一个线程对象向量。
标签: c++ multithreading stdvector