(g++ 4.6.3, cygwin, Windows 10)
I'm not sure if there is some way to speed up the following program using multithreading mechanisms (with which I'm quite unfamiliar):
// ab.h
class A {
// Member variables
...
// Member functions
A();
~A();
int foo_1();
void foo_2(std::vector<int>);
...
}
class B {
...
void schedule(std::vector<A>& va);
...
}
// b.cc
...
void B::schedule(std::vector<A>& va) {
std::vector<int> vc;
vc.resize(va.size());
for (... /* i from 0 to vc.size() */) {
...
vc[i] = va[i].foo_1();
...
}
for (... /* i from 0 to va.size() */) {
...
va[i].foo_2(vc);
...
}
// 5 more pairs of "for" loops like the above block
...
}
// main.cc
int main() {
...
std::vector<A> va;
// va.size() can be some large like 1000000
...
B b;
int simTime = 1000000000; // some large number of iterations
for (int clock = 0; clock != simTime; ++clock) {
b.schedule(va);
}
...
return 0;
}
So basically, I have a bunch of objects of type A
, which "advance" as clock
grows and meanwhile communicate with each other. My concerns are:
- I've just started rewriting each of my
for
loop pairs usingstd::async
andstd::get()
. Is this efficient? I've heard from somewhere thatstd::async
is most suitable to functions involving long time processing (like I/O) since the overhead of constructing/destructing a thread is not negligible (?). However, myfoo_1
andfoo_2
functions are not that "big". - If constructing/destructing a thread is expensive, then it should be better to create a bunch of threads needed only at the beginning. But in my case, that would be multiple "threads of objects" (I guess which is impossible) instead of "threads of member functions" (?). Is it possible to create a thread only once to serve one object but later "attach" its different member functions only without the constructing/destructing overhead? If so, how?
My code runs long (even after some optimization by myself), while there is a powerful 8-core server...