patterncppMinor
Is there a better way to thread this class function?
Viewed 0 times
thiswayfunctionbetterthreadthereclass
Problem
I have a class
When I call
I was thinking of doing something like:
My questions are:
between foo & bar?
To make this fun, you're only allowed to use pthread.h, no C++11 stuff :)
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_mappings;
void func() {
pthread_t threads[ foo_mappings.size() ];
map::iterator it = foo_mappings.begin();
int i=0;
for(it; it != foo_mappings.end() && i the_bar = this;
args->the_foo = it->first;
pthread_create( &threads[i], NULL, _threaded_foo_func, (void*) args);
}
for(int i=0; ithe_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 :)
Solution
How many instances of
Another approach that generally has better scalability is a thread pool. The basic idea is that you have a fixed number of threads that pull and execute tasks from a queue, resulting in better resource utilization.
foo are you going to have? Spawning a large number of threads or forking a large number of processes isn't going to scale well in terms of both CPU and memory resources.Another approach that generally has better scalability is a thread pool. The basic idea is that you have a fixed number of threads that pull and execute tasks from a queue, resulting in better resource utilization.
Context
StackExchange Code Review Q#11352, answer score: 3
Revisions (0)
No revisions yet.