Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Driver {
- public:
- // Spins up the thread
- void start();
- template<typename InputIt>
- void addCommands(InputIt begin, InputIt end)
- {
- // Zamkneme mutex
- std::unique_lock<std::mutex> lock(m_mutex);
- // Vlozime commandy a ulozime ci treba zobudit
- bool shouldNotify = !m_commands.size();
- m_commands.insert(m_commands.end(), begin, end);
- // Odomkneme a zobudime ak treba
- lock.unlock();
- if (shouldNotify)
- m_cv.notify_all();
- }
- private:
- std::mutex m_mutex;
- std::condition_variable m_cv;
- std::vector<Command> m_commands;
- bool processCommands(std::vector<Command> &&commands) const;
- void eventLoop();
- };
- void Driver::eventLoop()
- {
- bool isRunning = true;
- while (isRunning) {
- // Zamkneme mutex
- std::unique_lock<std::mutex> lock(m_mutex);
- // Pockame na commandy
- m_cv.wait(lock, [this]() { return !m_commands.size(); });
- // Vytiahneme commandy a odblokujeme mutex
- auto commands(std::move(m_commands));
- lock.unlock();
- // Processneme commandy bez mutexu
- // Ak pride command quit, processCommands sa ukonci a vrati false a ukoncime driver
- isRunning = processCommands(std::move(commands));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement