Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const int kDispatcherTaskExpiration = 2000;
- const auto kSystemTimeZero = std::chrono::system_clock::time_point(std::chrono::milliseconds(0));
- class Task
- {
- public:
- explicit Task(std::function<void(void)>&& f) :
- func_(std::move(f)) {}
- Task(uint32_t ms, std::function<void(void)>&& f) :
- expiration(std::chrono::system_clock::now() + std::chrono::milliseconds(ms)), func_(std::move(f)) {}
- virtual ~Task() = default;
- void operator()()
- {
- func_();
- }
- void SetDontExpire()
- {
- expiration = kSystemTimeZero;
- }
- bool HasExpired() const
- {
- if (expiration == kSystemTimeZero)
- {
- return false;
- }
- return expiration < std::chrono::system_clock::now();
- }
- protected:
- std::chrono::system_clock::time_point expiration = kSystemTimeZero;
- private:
- std::function<void(void)> func_;
- };
- Task* CreateTask(std::function<void(void)> f);
- Task* CreateTask(uint32_t expiration, std::function<void(void)> f);
- class Dispatcher
- {
- public:
- void AddTask(Task* task, bool push_front = false);
- Task* GetTask();
- bool HasTaskToExecute() const
- {
- return !taskList_.empty();
- }
- uint64_t GetDispatcherCycle() const
- {
- return dispatcherCycle_;
- }
- private:
- std::mutex taskLock_;
- std::list<Task*> taskList_;
- uint64_t dispatcherCycle_ = 0;
- };
- Task* CreateTask(std::function<void(void)> f)
- {
- return new Task(std::move(f));
- }
- Task* CreateTask(uint32_t expiration, std::function<void(void)> f)
- {
- return new Task(expiration, std::move(f));
- }
- void Dispatcher::AddTask(Task* task, bool push_front)
- {
- bool doSignal = false;
- taskLock_.lock();
- doSignal = taskList_.empty();
- if (push_front)
- {
- taskList_.push_front(task);
- }
- else
- {
- taskList_.push_back(task);
- }
- taskLock_.unlock();
- }
- Task* Dispatcher::GetTask()
- {
- // NOTE: second argument defer_lock is to prevent from immediate locking
- std::unique_lock<std::mutex> taskLockUnique(taskLock_, std::defer_lock);
- taskLockUnique.lock();
- if (!taskList_.empty)
- {
- Task* task = taskList_.front();
- taskList_.pop_front();
- taskLockUnique.unlock();
- if (!task->HasExpired())
- {
- ++dispatcherCycle_;
- return task;
- }
- delete task;
- }
- else
- {
- taskLockUnique.unlock();
- }
- return nullptr;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement