Advertisement
Guest User

ActiveObjectPattern

a guest
Apr 23rd, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.40 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3. #include <functional>
  4. #include <memory.h>
  5.  
  6. #include "TQueueTemplate.h"
  7.  
  8. using namespace std;
  9.  
  10. typedef function<void()> Callback;
  11.  
  12. class Active {
  13.  
  14. public:
  15.     Active();
  16.     ~Active();
  17.     void send(Callback Msg);
  18.  
  19.     Active(const Active&) = delete;
  20.     Active& operator=(const Active&) = delete;
  21.  
  22. private:
  23.     void doExit() {
  24.         mRunning = false;
  25.     }
  26.     void run();
  27.  
  28.     static void run_(void *ths);
  29. private:
  30.     std::thread mThread;
  31.     bool mRunning;
  32.     TQueueTemplate<Callback> mMsgQueue;
  33.  
  34. };
  35.  
  36. Active::Active() :
  37.         mThread(Active::run_, this), mRunning(true) {
  38. }
  39.  
  40. Active::~Active() {
  41.  
  42.     send(bind(&Active::doExit, this));
  43.     mThread.join();
  44. }
  45.  
  46. void Active::send(Callback Msg) {
  47.     mMsgQueue.put(Msg);
  48. }
  49.  
  50. void Active::run() {
  51.     std::cout << "Active" << std::endl;
  52.  
  53.     while (mRunning) {
  54.         Callback Cb = mMsgQueue.get();
  55.         Cb();
  56.     }
  57. }
  58.  
  59. void Active::run_(void *ths) {
  60.     reinterpret_cast<Active *>(ths)->run();
  61. }
  62.  
  63. /*********************************************************************************************************************/
  64.  
  65. void func() {
  66.     cout << "func" << endl;
  67. }
  68.  
  69. void func2(int i){
  70.     cout << "func: " << i << endl;
  71. }
  72.  
  73. /*********************************************************************************************************************/
  74.  
  75. int main() {
  76.     Active TestActive;
  77.  
  78.     TestActive.send(func);
  79.     TestActive.send(std::bind(func2, 2));
  80.  
  81.     return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement