fork download
  1. #define _GLIBCXX_USE_NANOSLEEP
  2. #define _GLIBCXX_USE_SCHED_YIELD
  3.  
  4. #include <thread>
  5. #include <chrono>
  6. #include <iostream>
  7. #include <functional>
  8. #include <string>
  9.  
  10. using namespace std;
  11.  
  12. template<class T>
  13. struct Return
  14. {
  15. Return(T val) : _val(val) {}
  16. void runCont(function<void (T)> k)
  17. {
  18. k(_val);
  19. }
  20.  
  21. T _val;
  22. };
  23.  
  24. template<class T, class C1, class C2>
  25. struct Bind
  26. {
  27. Bind(C1 const &ktor, function<C2(T)> rest)
  28. : _ktor(ktor), _rest(rest)
  29. {}
  30.  
  31. void runCont(function <void(T)> k)
  32. {
  33. function<C2(T)> rest = _rest;
  34. function<void(T)> lambda = [k, rest](T a)
  35. {
  36. return rest(a).runCont(k);
  37. };
  38. _ktor.runCont(lambda);
  39. }
  40.  
  41. C1 _ktor;
  42. function<C2(T)> _rest;
  43. };
  44.  
  45. void asyncApi(function<void(string)> handler)
  46. {
  47. thread th([handler](){
  48. cout << "Started async\n";
  49. this_thread::sleep_for(chrono::seconds(3));
  50. handler("Done async");
  51. });
  52. th.detach();
  53. }
  54.  
  55. // Continuator
  56. struct AsyncApi {
  57. void runCont(function<void(string)> k) {
  58. asyncApi(k);
  59. }
  60. };
  61.  
  62. struct Loop {
  63. Loop(string s) : _s(s) {}
  64. void runCont(function<void(string)> k) {
  65. cout << "fuga:" << _s << endl;
  66. Bind<string, AsyncApi, Loop> (
  67. AsyncApi(),
  68. [](string s)
  69. {
  70. return Loop(s); // recursion?
  71. }).runCont(k);
  72. }
  73. string _s;
  74. };
  75.  
  76. int main()
  77. {
  78. Loop("Loop: ").runCont([](string s)
  79. {
  80. cout << "hoge:" << s << endl;
  81. });
  82.  
  83. for(int i = 0; i < 200; ++i)
  84. {
  85. cout << "for : " << i << endl;
  86. this_thread::sleep_for(chrono::seconds(1));
  87. }
  88. }
  89.  
Time limit exceeded #stdin #stdout 5s 19464KB
stdin
Standard input is empty
stdout
fuga:Loop: 
for : 0
Started async
for : 1
for : 2
fuga:Done async
Started async
for : 3
for : 4
for : 5
fuga:Done async
Started async
for : 6
for : 7
for : 8
fuga:Done async
Started async
for : 9
for : 10