view modules/timer/timer.hpp @ 515:409cf1aa4af9

Timer: add experimental threaded timers
author David Demelier <markand@malikania.fr>
date Wed, 01 Jun 2016 15:41:22 +0200
parents
children 25e6380d0849
line wrap: on
line source

#ifndef TIMER_HPP
#define TIMER_HPP

#include <atomic>
#include <condition_variable>
#include <chrono>
#include <cstdint>
#include <functional>
#include <mutex>
#include <thread>

class Timer {
public:
	enum Type {
		Repeat,
		Single
	};

private:
	Type m_type;
	std::atomic<bool> m_alive{true};
	std::thread m_thread;
	std::mutex m_mutex;
	std::condition_variable m_condition;
	std::function<void ()> m_handler;
	std::uint32_t m_delay;

	void call();
	void wait();
	void runOne();
	void runForever();

public:
	inline Timer(Type type, std::uint32_t delay) noexcept
		: m_type(type)
		, m_delay(delay)
	{
	}

	inline ~Timer()
	{
		stop();
	}

	inline const std::function<void ()> &handler() const noexcept
	{
		return m_handler;
	}

	inline std::function<void ()> &handler() noexcept
	{
		return m_handler;
	}

	inline void setHandler(std::function<void ()> handler)
	{
		m_handler = std::move(handler);
	}

	void start();

	void stop();
};

#endif // !TIMER_HPP