I have a class bar that keeps track of N instances of class foo in a std::map (so N = map.size()).
When I call bar::func I want to have N threads that call foo::foo_func.
foo::foo_func requires multiple arguments though, namely the instance of bar that it's related to.
I was thinking of doing something like:
void * _threaded_foo_func(void *);
struct box {
bar * the_bar;
foo * the_foo;
};
class bar {
class sub_bar {
// stuff
};
map<foo*, sub_bar*> foo_mappings;
void func() {
pthread_t threads[ foo_mappings.size() ];
map<foo*, sub_bar*>::iterator it = foo_mappings.begin();
int i=0;
for(it; it != foo_mappings.end() && i < foo_mappings.size(); ++it, ++i) {
box * args = new args();
args->the_bar = this;
args->the_foo = it->first;
pthread_create( &threads[i], NULL, _threaded_foo_func, (void*) args);
}
for(int i=0; i<bar_mappings.size(); ++i) {
pthread_join(threads[i], NULL);
}
}
};
void * _threaded_foo_func(void * args) {
box * b = (box*) args;
bar * the_bar = b->the_bar;
foo * the_foo = b->the_foo;
the_foo->foo_func(the_bar);
return NULL;
}
My questions are:
- Is there a better way to do this? Cleaner? Thoughts on using
fork()? - Does this look like a poor design of the relationship between foo & bar?
To make this fun, you're only allowed to use pthread.h, no C++11 stuff :)
std::thread? – Rob Apr 30 '12 at 16:55