Skip to content

Instantly share code, notes, and snippets.

@dhollman
Created September 9, 2014 11:42
Show Gist options
  • Save dhollman/0b8d4b0868a3e9f2ea83 to your computer and use it in GitHub Desktop.
Save dhollman/0b8d4b0868a3e9f2ea83 to your computer and use it in GitHub Desktop.
inline void
do_threaded(int nthread, const std::function<void(int)>& f){
boost::thread_group compute_threads;
// Loop over number of threads
for(int ithr = 0; ithr < nthread; ++ithr) {
// create each thread that runs f
compute_threads.create_thread([&, ithr](){
// run the work
f(ithr);
});
}
// join the created threads
compute_threads.join_all();
}
// or, you can use this fancier version with unnecessary complication
template<typename Function, typename... Args>
inline void
do_threaded(int nthread, Args... args, const Function& f){
boost::thread_group compute_threads;
// Loop over number of threads
for(int ithr = 0; ithr < nthread; ++ithr) {
// create each thread that runs f
compute_threads.create_thread([&, ithr](){
// run the work
f(ithr, args...);
});
}
// join the created threads
compute_threads.join_all();
}
// Use it like this
int main() {
int nthread = 8; // for instance
// Quick, OpenMP-like threading with C++11 lambdas
do_threaded(nthread, [&](int ithr) {
//...
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment