需要帮助在C ++中实现一个timer / ticker类 [英] Need help in implementation of a timer/ticker class in C++

查看:261
本文介绍了需要帮助在C ++中实现一个timer / ticker类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要帮助实现具有start / stop / pause功能的ticker类,可分配的回调(onTick),在每个间隔跨度上在单独的线程上执行。间隔跨度是可指定和可更新的。希望它应该是跨平台的。

Need help in implementing a ticker class with start/stop/pause functionality, assignable callback (onTick) with execution on a separate thread every interval span. Interval span is specifiable and update-able. Hopefully it should be cross-platform.

这是我的天真尝试,但它不是好的(while循环在start()当前是阻塞,但理想情况下应该运行在一个单独的线程,但我不能弄清楚如何实现它)作为我很漂亮noob在C + +多线程模型:

Here is my naive attempt, but it's not good (the while loop in start() is blocking currently, but ideally it should run on a separate thread but I can't figure out how to achieve it) as I'm pretty noob in C++ multithreading model:

#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;
};

我的尝试完全错了,还是很接近?

I'm a completely wrong in my attempt or it's pretty close?

推荐答案

考虑下面的代码和使用示例。我希望我能正确理解你。
只需在单独的线程中运行,而循环。

Consider the following code with example of usage. I hope I understood you correctly. Just run your while loop in a separate thread.

#include <cstdint>
#include <functional>
#include <chrono>
#include <thread>
#include <future>
#include <condition_variable>
#include <iostream>
#include <mutex>

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;
        std::thread run(&Ticker::timer_loop, this);
        run.detach();
    }

    void stop () { _running = false; }

    void setDuration(std::chrono::duration<int64_t, std::nano> tickInterval)
    {
        _tickIntervalMutex.lock();
        _tickInterval = tickInterval;
        _tickIntervalMutex.unlock();
    }

private:
    void timer_loop()
    {
        while (_running) {
            std::thread run(_onTick );
            run.detach();

            _tickIntervalMutex.lock();
            std::chrono::duration<int64_t, std::nano> tickInterval = _tickInterval;
            _tickIntervalMutex.unlock();
            std::this_thread::sleep_for( tickInterval );
        }
    }

    on_tick_t           _onTick;
    tick_interval_t     _tickInterval;
    volatile bool       _running;
    std::mutex          _tickIntervalMutex;
};

void tick()
{
    std::cout << "tick\n";
}

void main()
{
    std::chrono::duration<int, std::milli> timer_duration1(1000);
    std::chrono::duration<int, std::milli> timer_duration2(500);
    std::chrono::duration<int> main_wait(5);

    Ticker ticker(std::function<void()>(tick), timer_duration1);
    ticker.start();

    std::this_thread::sleep_for(main_wait);
    ticker.setDuration(timer_duration2);
    std::this_thread::sleep_for(main_wait);
    ticker.stop();
}

这篇关于需要帮助在C ++中实现一个timer / ticker类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆