#define _GLIBCXX_USE_NANOSLEEP
#define _GLIBCXX_USE_SCHED_YIELD
#include <thread>
#include <chrono>
#include <iostream>
#include <functional>
#include <string>
using namespace std;
template<class T>
struct Return
{
Return(T val) : _val(val) {}
void runCont(function<void (T)> k)
{
k(_val);
}
T _val;
};
template<class T, class C1, class C2>
struct Bind
{
Bind(C1 const &ktor, function<C2(T)> rest)
: _ktor(ktor), _rest(rest)
{}
void runCont(function <void(T)> k)
{
function<C2(T)> rest = _rest;
function<void(T)> lambda = [k, rest](T a)
{
return rest(a).runCont(k);
};
_ktor.runCont(lambda);
}
C1 _ktor;
function<C2(T)> _rest;
};
void asyncApi(function<void(string)> handler)
{
thread th([handler](){
cout << "Started async\n";
this_thread::sleep_for(chrono::seconds(3));
handler("Done async");
});
th.detach();
}
// Continuator
struct AsyncApi {
void runCont(function<void(string)> k) {
asyncApi(k);
}
};
struct Loop {
Loop(string s) : _s(s) {}
void runCont(function<void(string)> k) {
cout << "fuga:" << _s << endl;
Bind<string, AsyncApi, Loop> (
AsyncApi(),
[](string s)
{
return Loop(s); // recursion?
}).runCont(k);
}
string _s;
};
int main()
{
Loop("Loop: ").runCont([](string s)
{
cout << "hoge:" << s << endl;
});
for(int i = 0; i < 200; ++i)
{
cout << "for : " << i << endl;
this_thread::sleep_for(chrono::seconds(1));
}
}