Skip to content

Instantly share code, notes, and snippets.

Created September 9, 2017 15:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/1020ac7692484fb51a309f55fc70ad66 to your computer and use it in GitHub Desktop.
Save anonymous/1020ac7692484fb51a309f55fc70ad66 to your computer and use it in GitHub Desktop.
Play arround with threads while thinking of Akka Graphs. JOKE code dont use in production
#include <algorithm>
#include <chrono>
#include <functional>
#include <future>
#include <iostream>
#include <thread>
#include <vector>
#define DEBUG(M) std::cout << M
template <typename T> struct Expr {
virtual std::future<T> run() = 0;
};
// Data Provider, return 1 output of Type T
template <typename T> struct DataProvider : public Expr<T> {
DataProvider(T v) : value(v) {}
std::future<T> run() override {
std::promise<T> p;
p.set_value(value);
DEBUG("Providing data") << std::endl;
return p.get_future();
}
T value;
};
// Combinator, takes 2 inputs and return 1 output both of type T
template <typename T> struct Add : public Expr<T> {
Add(Expr<T> *a, Expr<T> *b) : a(a), b(b) {}
std::future<T> run() override {
std::future<T> fa = a->run();
std::future<T> fb = b->run();
DEBUG("waiting Data from Provider") << std::endl;
fa.wait();
fb.wait();
DEBUG("Get Data from Provider") << std::endl;
const T &va = fa.get();
const T &vb = fb.get();
DEBUG("Compute ") << va << " + " << vb << std::endl;
return std::async([](const T &va, const T &vb) -> T { return va + vb; }, va,
vb);
}
Expr<T> *a;
Expr<T> *b;
};
// Get an input of Type I and return 1 output of type O
template <typename I, typename O> struct Map : public Expr<O> {
Map(Expr<I> *v, const std::function<O(I)> &convert)
: expr(v), convert(convert) {}
std::future<O> run() override {
std::future<I> val = expr->run();
val.wait();
DEBUG("Convert Value to new Type ") << std::endl;
std::promise<O> p;
p.set_value(convert(val.get()));
return p.get_future();
}
const std::function<O(I)> &convert;
Expr<I> *expr;
};
int main() {
auto data_provider1 = new DataProvider<double>(2);
auto data_provider2 = new DataProvider<double>(3);
auto job =
new Map<double, int>(new Add<double>(data_provider1, data_provider2),
[](double d) -> int { return d; });
auto result = job->run();
result.wait();
std::cout << result.get() << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment