Skip to content

Instantly share code, notes, and snippets.

@shivendra14
Created September 14, 2017 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shivendra14/0548302e802d23ebfdaba218886beebe to your computer and use it in GitHub Desktop.
Save shivendra14/0548302e802d23ebfdaba218886beebe to your computer and use it in GitHub Desktop.
A simple multi threaded cpp-11 code
#include <iostream>
#include <string>
#include <vector>
#include <atomic>
#include <thread>
#include <future>
template <class F>
void par_for(int begin, int end, F fn) {
std::atomic<int> idx;
idx = begin;
int num_cpus = std::thread::hardware_concurrency();
std::vector<std::future<void>> futures (num_cpus);
for (int cpu = 0; cpu != num_cpus; ++cpu) {
futures[cpu] = std::async(
std::launch::async,
[cpu, &idx, end, &fn]() {
for (;;) {
int i = idx++;
if (i >= end) break;
fn(i, cpu);
}
}
);
}
for (int cpu = 0; cpu != num_cpus; ++cpu) {
futures[cpu].get();
}
}
int main()
{
par_for(
10, 20,
[](int idx, int cpu) {
printf("task %d running on cpu %d\n", idx, cpu);
}
);
}
@shivendra14
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment