fork download
  1. #include <iostream>
  2. #include <queue>
  3. #include <functional>
  4. #include <utility>
  5. //using namespace std;
  6.  
  7. using Offset = int; // next frame, or "after previous Entry was done", ...
  8. using DeferredFn = std::function<void()>;
  9.  
  10. struct Entry {
  11. Entry (Offset o, DeferredFn f) : offset(o), func {std::move(f)} {}
  12. Offset offset;
  13. DeferredFn func;
  14. };
  15. class MsgQ {
  16. public:
  17. MsgQ () : _q() {}
  18. ~MsgQ () {}
  19. void push (Offset offset, DeferredFn function) {
  20. _q.push(Entry{offset, std::move(function)});
  21. }
  22. bool process () {
  23. // example! In reality it reacts on e.offs somehow!
  24. if (!_q.empty()) {
  25. auto e = _q.front();
  26. e.func(); // execute
  27. _q.pop();
  28. return true;
  29. }
  30. return false; // Q empty!
  31. }
  32. private:
  33. std::queue<Entry> _q;
  34. };
  35.  
  36. int oapiFoo(int a, int b) { auto res = a+b; std::cout << "done " << res; return res; };
  37. void oapiBar(int x) { std::cout << "done " << x; };
  38.  
  39. int main() {
  40. int x = 1;
  41. int y = 2;
  42. int z = 0;
  43. MsgQ q;
  44. q.push(1, [x,y,&z](){ z = oapiFoo(x, y); });
  45. // ...
  46. y++; // the lambda captured 'y'-state before, so try to avoid it ;)
  47. // ...
  48. q.push(10, [](){ oapiBar(42); });
  49. // ...
  50. q.process();
  51. q.process();
  52. return 0;
  53. }
Success #stdin #stdout 0s 4248KB
stdin
Standard input is empty
stdout
done 3done 42