Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <functional>
- #include <vector>
- #include <chrono>
- #include <thread>
- #include <mutex>
- class Timer {
- private:
- std::function<void(void *)> _callback;
- uint8_t _stopped;
- uint8_t _done;
- void* _state;
- uint64_t _delayMS;
- std::chrono::nanoseconds _acc;
- std::chrono::time_point<std::chrono::system_clock> _lastUpdate = std::chrono::system_clock::now();
- public:
- Timer( uint64_t delayMS,
- const std::function<void(void *)> callback,
- void* state) {
- _stopped = 1;
- _callback = callback;
- _state = state;
- _delayMS = delayMS;
- enqueue_timer(this);
- }
- void start() { _stopped = 0; }
- void stop() { _stopped = 1; }
- private:
- void update() {
- auto temp = _lastUpdate;
- _lastUpdate = std::chrono::system_clock::now();
- if(_done == 1)
- return;
- if (_stopped == 0) {
- auto now = std::chrono::system_clock::now();
- auto delta = now - temp;
- _acc += delta;
- auto acc_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
- _acc
- );
- if(_delayMS <= acc_ms.count()){
- _done = 1;
- _callback(_state);
- }
- }
- }
- // static part
- private:
- static std::vector<Timer*> __timers;
- static uint64_t __timer_state;
- static std::thread __timer_worker_thread;
- static std::mutex __timer_sync_root;
- private:
- static void enqueue_timer(Timer *timer)
- {
- __timer_sync_root.lock();
- __timers.push_back(timer);
- __timer_sync_root.unlock();
- }
- public:
- static void init(uint64_t delayMS) {
- __timer_worker_thread = std::thread([=]() {
- while (__timer_state == 0) {
- __timer_sync_root.lock();
- for(size_t i = __timers.size() - 1; i >= 0; i--){
- auto timer = __timers[i];
- if(timer->_done){
- delete __timers[i];
- auto position = __timers.begin() + i;
- __timers.erase(position);
- }
- }
- for(auto i = 0; i < __timers.size(); i++){
- auto timer = __timers[i];
- timer->update();
- }
- __timer_sync_root.unlock();
- std::this_thread::sleep_for(std::chrono::milliseconds(delayMS));
- }
- });
- }
- static void signalAppStopped() {
- __timer_state = 1;
- __timer_worker_thread.join();
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement