c++ - 面向对象的C++多线程

标签 c++ multithreading c++11

我已经开始在 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/

相关文章:

c++ - 对于我的std::pair特化,我应该在哪里定义运算符>>?

c++ - OpenMP 嵌套循环,每个 `for` 循环之间都有代码

c++ - 删除与运算符删除(和空指针)

c++ - 利用 move 语义自动隐式生成 ctors

c++ - 静态断言和 SFINAE

c++组合来自两个(或更多)参数包的值

C++/调试(AIX 上的 g++)递归快速排序导致段错误

java volatile 数组,我的测试结果与预期不符

java - 寻求有关如何避免死锁的建议

C++ 内存排序