Created
September 14, 2017 17:48
-
-
Save shivendra14/0548302e802d23ebfdaba218886beebe to your computer and use it in GitHub Desktop.
A simple multi threaded cpp-11 code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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); | |
} | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://coliru.stacked-crooked.com/a/332f5d89cfb17ef6