【发布时间】:2017-11-05 00:48:16
【问题描述】:
使用基于this boost asio 的线程池,在这种情况下,该类被命名为ThreadPool,我想并行化std::vector<boost::shared_ptr<T>> 类型的向量的填充,其中T 是一个struct,其中包含一个std::vector<int> 类型的向量,其内容和大小在结构初始化后动态确定。
不幸的是,我在 c++ 和多线程方面都是新手,所以我解决这个问题的尝试非常失败。这是一个过于简化的示例程序,它对任务的非线程和线程版本进行计时。线程版本的性能是可怕的......
#include "thread_pool.hpp"
#include <ctime>
#include <iostream>
#include <vector>
using namespace boost;
using namespace std;
struct T {
vector<int> nums = {};
};
typedef boost::shared_ptr<T> Tptr;
typedef vector<Tptr> TptrVector;
void create_T(const int i, TptrVector& v) {
v[i] = Tptr(new T());
T& t = *v[i].get();
for (int i = 0; i < 100; i++) {
t.nums.push_back(i);
}
}
int main(int argc, char* argv[]) {
clock_t begin, end;
double elapsed;
// define and parse program options
if (argc != 3) {
cout << argv[0] << " <num iterations> <num threads>" << endl;
return 1;
}
int iterations = stoi(argv[1]),
threads = stoi(argv[2]);
// create thread pool
ThreadPool tp(threads);
// non-threaded
cout << "non-thread" << endl;
begin = clock();
TptrVector v(iterations);
for (int i = 0; i < iterations; i++) {
create_T(i, v);
}
end = clock();
elapsed = double(end - begin) / CLOCKS_PER_SEC;
cout << elapsed << " seconds" << endl;
// threaded
cout << "threaded" << endl;
begin = clock();
TptrVector v2(iterations);
for (int i = 0; i < iterations; i++) {
tp.submit(boost::bind(create_T, i, v2));
}
tp.stop();
end = clock();
elapsed = double(end - begin) / CLOCKS_PER_SEC;
cout << elapsed << " seconds" << endl;
return 0;
}
在进行了一些挖掘之后,我认为性能不佳可能是由于线程争夺内存访问,但我的新手状态让我无法利用这种洞察力。 您能否使用多个线程(最好是在线程池中)有效地填充指针向量?
【问题讨论】:
标签: c++ multithreading boost