Skip to content

Instantly share code, notes, and snippets.

@mbitsnbites
Last active May 10, 2019 06:23
Show Gist options
  • Save mbitsnbites/26f54bf151a01bc8a90cd09a0c21b673 to your computer and use it in GitHub Desktop.
Save mbitsnbites/26f54bf151a01bc8a90cd09a0c21b673 to your computer and use it in GitHub Desktop.
A simple thread pool based "parallel for" implementation for C++11.
#include <atomic>
#include <thread>
template <typename COUNT_T, typename BODY_T>
void parallel_for(const COUNT_T count, BODY_T body) {
std::vector<std::thread> workers;
std::atomic<COUNT_T> next_job_id(0);
for (unsigned int i = std::thread::hardware_concurrency(); i > 0; --i) {
workers.emplace_back([&]() {
while (true) {
const auto job_id = next_job_id++;
if (job_id >= count) {
return;
}
body(job_id);
}
});
}
for (auto& worker : workers) {
worker.join();
}
}
// ...
void example(const std::vector<item_t>& items) {
parallel_for(items.size(), [&](std::size_t k) {
std::cout << "Processing item " << k << "\n";
const auto& item = items[k];
// ...
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment