view modules/timer/timer.cpp @ 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

#include <cassert>

#include "timer.hpp"

void Timer::call()
{
	if (m_alive && m_handler)
		m_handler();
}

void Timer::wait()
{
	std::unique_lock<std::mutex> lock(m_mutex);

	m_condition.wait_for(lock, std::chrono::milliseconds(m_delay), [&] () {
		return static_cast<bool>(!m_alive);
	});
}

void Timer::runOne()
{
	wait();
	call();
}

void Timer::runForever()
{
	while (m_alive) {
		wait();
		call();
	}
}

void Timer::start()
{
	assert(!m_thread.joinable());

	m_alive = true;

	if (m_type == Single)
		m_thread = std::thread(std::bind(&Timer::runOne, this));
	else
		m_thread = std::thread(std::bind(&Timer::runForever, this));
}

void Timer::stop()
{
	if (m_thread.joinable()) {
		m_alive = false;
		m_condition.notify_one();
		m_thread.join();
	}
}








#include <iostream>

int main()
{
	Timer timer(Timer::Repeat, 500);

	timer.setHandler([] () { std::puts("tu me chatouilles"); });
	auto f = std::move(timer.handler());
	timer.setHandler([&] () {
		std::puts("preums");
		f();
	});
	timer.start();

	std::this_thread::sleep_for(std::chrono::seconds(2));
	std::puts("Je coupe le son...");
	timer.stop();
	std::this_thread::sleep_for(std::chrono::seconds(5));
	std::puts("Je remets le son...");
	timer.start();
	std::this_thread::sleep_for(std::chrono::seconds(2));

	return 0;
}