Advertisement
xgallom

eventLoop

Jan 13th, 2022
821
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. class Driver {
  2. public:
  3.     // Spins up the thread
  4.     void start();
  5.  
  6.     template<typename InputIt>
  7.     void addCommands(InputIt begin, InputIt end)
  8.     {
  9.         // Zamkneme mutex
  10.         std::unique_lock<std::mutex> lock(m_mutex);
  11.  
  12.         // Vlozime commandy a ulozime ci treba zobudit
  13.         bool shouldNotify = !m_commands.size();
  14.         m_commands.insert(m_commands.end(), begin, end);
  15.        
  16.         // Odomkneme a zobudime ak treba
  17.         lock.unlock();
  18.         if (shouldNotify)
  19.             m_cv.notify_all();
  20.     }
  21.  
  22. private:
  23.     std::mutex m_mutex;
  24.     std::condition_variable m_cv;
  25.     std::vector<Command> m_commands;
  26.  
  27.     bool processCommands(std::vector<Command> &&commands) const;
  28.     void eventLoop();
  29. };
  30.  
  31. void Driver::eventLoop()
  32. {
  33.     bool isRunning = true;
  34.  
  35.     while (isRunning) {
  36.         // Zamkneme mutex
  37.         std::unique_lock<std::mutex> lock(m_mutex);
  38.  
  39.         // Pockame na commandy
  40.         m_cv.wait(lock, [this]() { return !m_commands.size(); });
  41.            
  42.         // Vytiahneme commandy a odblokujeme mutex
  43.         auto commands(std::move(m_commands));
  44.         lock.unlock();
  45.  
  46.         // Processneme commandy bez mutexu
  47.         // Ak pride command quit, processCommands sa ukonci a vrati false a ukoncime driver
  48.         isRunning = processCommands(std::move(commands));
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement