Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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(
[cpu, &idx, end, &fn]() {
for (;;) {
int i = idx++;
if (i >= end) break;
fn(i, cpu);
for (int cpu = 0; cpu != num_cpus; ++cpu) {
int main()
10, 20,
[](int idx, int cpu) {
printf("task %d running on cpu %d\n", idx, cpu);

This comment has been minimized.

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