异步定时器

需要一个定时器,想需要的功能有异步或者同线程阻塞式,直接上代码

#pragma once

#include
#include
#include
#include
#include
#include
#include

class Timer{
public:
	Timer() :expired_(true), try_to_expire_(false){
	}

	Timer(const Timer& t){
		expired_ = t.expired_.load();
		try_to_expire_ = t.try_to_expire_.load();
	}
	~Timer(){
		Expire();
	}

	void StartTimer(int interval, std::function task){
		if (expired_ == false)
		{
			return;
		}
		expired_ = false;
		std::thread([this, interval, task]()
		{
			while (!try_to_expire_)
			{
				std::this_thread::sleep_for(std::chrono::milliseconds(interval));
				task();
			}
			{
				std::lock_guard locker(mutex_);
				expired_ = true;
				expired_cond_.notify_one();
			}
		}).detach();
	}

	void Expire(){
		if (expired_)
		{
			return;
		}

		if (try_to_expire_)
		{
			return;
		}
		try_to_expire_ = true;
		{
			std::unique_lock locker(mutex_);
			expired_cond_.wait(locker, [this]{return expired_ == true; });
			if (expired_ == true)
			{
				try_to_expire_ = false;
			}
		}
	}

	template
	void SyncWait(int after, callable&& f, arguments&&... args)
	{

		std::function::type()> task
			(std::bind(std::forward(f), std::forward(args)...));
		std::this_thread::sleep_for(std::chrono::milliseconds(after));
		task();
	}
	template
	void AsyncWait(int after, callable&& f, arguments&&... args)
	{
		std::function::type()> task
			(std::bind(std::forward(f), std::forward(args)...));

		std::thread([after, task]()
		{
			std::this_thread::sleep_for(std::chrono::milliseconds(after));
			task();
		}).detach();
	}

private:
	std::atomic expired_;
	std::atomic try_to_expire_;
	std::mutex mutex_;
	std::condition_variable expired_cond_;
};

定时器实现完毕,但是对于图形渲染方面,或者回调必须在主线程进行的,异步达不到要求,需重新实现

你可能感兴趣的:(C/C++编程语言)