Reputation: 1225
I've started using some basic threading in c++0x to speed things up. For a trivial example which does nothing except test speed:
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();
}
and that works quite well. My question is somewhat a general one, namely how to generalize the above idea to working with member functions. Say I have 10 Rope(s), and each rope has several (single-threaded) member functions, computeTorques(), computeForces(), etc. Assuming the Rope(s) do not share memory/resources, is there a way I can multi-thread calling each member function of each Rope without explicitly having to change the (single-threaded) code within the Rope?
Upvotes: 2
Views: 3374
Reputation: 4103
Use 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();
}
EDITED: Using lambda would be better.
for(auto& r : ropes)
t.push_back(std::thread([&]{ r.compute(); }));
Upvotes: 3
Reputation: 283793
It's completely dependent on the implementation of your object.
For some objects this would be safe, for others you could have trouble.
Upvotes: -1