参考:http://codereview.stackexchange.com/questions/40915/simple-multithread-timer
本文实现了一个多线程C++定时器,具备设置singleshot,start(),stop()等功能。
代码如下:
Timer.h:
#ifndef TIMER_H #define TIMER_H #include <thread> #include <chrono> class Timer { public: typedef std::chrono::milliseconds Interval; typedef std::function<void(void)> Timeout; Timer(const Timeout &timeout); Timer(const Timeout &timeout, const Interval &interval, bool singleShot = true); void start(bool multiThread = false); void stop(); bool running() const; void setSingleShot(bool singleShot); bool isSingleShot() const; void setInterval(const Interval &interval); const Interval &interval() const; void setTimeout(const Timeout &timeout); const Timeout &timeout() const; private: std::thread _thread; bool _running = false; bool _isSingleShot = true; Interval _interval = Interval(0); Timeout _timeout = nullptr; void _temporize(); void _sleepThenTimeout(); }; #endif // TIMER_H
Timer.cpp:
#include "Timer.h" Timer::Timer(const Timeout &timeout) : _timeout(timeout) { } Timer::Timer(const Timer::Timeout &timeout, const Timer::Interval &interval, bool singleShot) : _isSingleShot(singleShot), _interval(interval), _timeout(timeout) { } void Timer::start(bool multiThread) { if (this->running() == true) return; _running = true; if (multiThread == true) { _thread = std::thread( &Timer::_temporize, this); } else{ this->_temporize(); } } void Timer::stop() { _running = false; _thread.join(); } bool Timer::running() const { return _running; } void Timer::setSingleShot(bool singleShot) { if (this->running() == true) return; _isSingleShot = singleShot; } bool Timer::isSingleShot() const { return _isSingleShot; } void Timer::setInterval(const Timer::Interval &interval) { if (this->running() == true) return; _interval = interval; } const Timer::Interval &Timer::interval() const { return _interval; } void Timer::setTimeout(const Timeout &timeout) { if (this->running() == true) return; _timeout = timeout; } const Timer::Timeout &Timer::timeout() const { return _timeout; } void Timer::_temporize() { if (_isSingleShot == true) { this->_sleepThenTimeout(); } else { while (this->running() == true) { this->_sleepThenTimeout(); } } } void Timer::_sleepThenTimeout() { std::this_thread::sleep_for(_interval); if (this->running() == true) this->timeout()(); }
main.cpp:
#include <iostream> #include "Timer.h" using namespace std; int main(void) { Timer tHello([]() { cout << "Hello!" << endl; }); tHello.setSingleShot(false); tHello.setInterval(Timer::Interval(1000)); tHello.start(true); Timer tStop([&]() { tHello.stop(); }); tStop.setSingleShot(true); tStop.setInterval(Timer::Interval(3000)); tStop.start(); while (1){} return 0; }
编译:
g++ -std=c++0x -pthread main.cpp Timer.cpp -o timer
运行:
./timer
效果:
[root@localhost timer_test]# ./timer Hello! Hello! Hello!
文章的脚注信息由WordPress的wp-posturl插件自动生成