我已经开始在 c++0x 中使用一些基本线程来加快速度。对于一个除了测试速度之外不执行任何操作的简单示例:
void my_thread_func(int n, int steps, int offset)
{
double a[n];
for (int i=0; i<n; i++)
a[i] = i + offset;
for (int step=0; step<steps; step++)
for (int i=0; i<n; i++)
a[i] = sin(a[i]);
}
int main()
{
std::vector<std::thread> t;
for (int i=0; i<numRuns; i++)
t.push_back(std::thread(my_thread_func, n, steps, i));
for (int i=0; i<numRuns; i++)
t[i].join();
}
效果很好。我的问题有点笼统,即如何将上述想法推广到使用成员函数。假设我有 10 根绳子,每根绳子都有几个(单线程)成员函数,computeTorques()、computeForces() 等。假设绳子不共享内存/资源,有没有办法我是否可以多线程调用每个 Rope 的每个成员函数,而无需显式更改 Rope 内的(单线程)代码?
最佳答案
使用std::bind
。
class Rope
{
...
void compute();
};
int main()
{
Rope ropes[10];
std::vector<std::thread> t;
for(auto& r : ropes)
t.push_back(std::thread(std::bind(&Rope::compute, &r)));
for(auto& th : t)
th.join();
}
已编辑:使用 lambda 会更好。
for(auto& r : ropes)
t.push_back(std::thread([&]{ r.compute(); }));
关于c++ - 面向对象的C++多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9264405/