【发布时间】:2014-07-16 10:50:49
【问题描述】:
在实现具有启动/停止/暂停功能、可分配回调 (onTick) 的代码类时需要帮助,每个间隔跨度在单独的线程上执行。间隔跨度是可指定和可更新的。希望它应该是跨平台的。
这是我的幼稚尝试,但这并不好(start() 中的 while 循环目前正在阻塞,但理想情况下它应该在单独的线程上运行,但我不知道如何实现它)因为我是C++ 多线程模型中的漂亮菜鸟:
#include <cstdint>
#include <functional>
#include <chrono>
#include <thread>
#include <future>
class Ticker {
public:
typedef std::chrono::duration<int64_t, std::nano> tick_interval_t;
typedef std::function<void()> on_tick_t;
Ticker (std::function<void()> onTick, std::chrono::duration<int64_t, std::nano> tickInterval)
: _onTick (onTick)
, _tickInterval (tickInterval)
, _running (false) {}
~Ticker () {}
void start () {
if (_running) return;
_running = true;
while (_running) {
std::async( std::launch::async, _onTick );
std::this_thread::sleep_for( _tickInterval );
}
}
void stop () { _running = false; }
private:
on_tick_t _onTick;
tick_interval_t _tickInterval;
bool _running;
};
我的尝试完全错了,还是非常接近?
【问题讨论】:
-
参考
boost::asio::deadline_timer:boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference/… -
谢谢,但我不确定这是否是我要找的。 :) 我正在寻找一个会在每个滴答声上调用回调的代码。你有没有看过我的尝试,我的尝试完全错了,还是非常接近?
标签: c++ multithreading timer cross-platform ticker