C++ : Modifying a timer

标签 c++ timer

我目前正在使用类在 C++ 中制作计时器。

我有以下类声明:

class time
{
   int  min;
   int  sec ;
   public:
    void start()
      {
        for(int j = 0; j<60; j++)
            {
                if(min == 59)
               min = 0;
            }

            for(int k = 0; k<60; k++)
            {
            if(sec == 59)
                sec = 0;
            cout<<min<<" : "<<sec<<endl;
            sec++;
            Sleep(1000);
            system("Cls");
            }
            min++;
        }

}a;

所以目前我可以通过 a.start() 启动计时器 我正在寻找一种方法来停止它。有什么想法吗?

感谢帮助:)

最佳答案

如果您希望在任何给定时刻终止计时器,则需要一个线程。我在 gcc 4.9.2 上实现了下面的一个。

#include <iostream>
#include <iomanip>
#include <thread>
#include <chrono>

class Timer
{
public:
    Timer(uint minutes, uint seconds)
        : m_minutes(minutes)
        , m_seconds(seconds)
        , m_active(false)
    { }

    void
        start()
        {
            m_active = true;
            m_thread = std::thread([=]() 
            {
                while(m_active && (m_minutes | m_seconds))
                {
                    if(!m_seconds)
                    {
                        m_seconds = 59;
                        m_minutes = m_minutes - 1;
                    }

                    std::cout << std::setw(2) << std::setfill('0') << m_minutes   << "m" << " "
                              << std::setw(2) << std::setfill('0') << m_seconds-- << "s" << std::endl;
                    std::this_thread::sleep_for(std::chrono::seconds(1));
                }
            });
        }

    void
        stop()
        {
            m_active = false;
            m_thread.join();
        }

private:
    std::thread m_thread;
    uint        m_minutes;
    uint        m_seconds;
    bool        m_active;
};

int main( )
{
    Timer t(0, 10);

    t.start();
    std::this_thread::sleep_for(std::chrono::seconds(7));
    t.stop();

    return 0;
}

输出:

00m 10s
00m 09s
00m 08s
00m 07s
00m 06s
00m 05s
00m 04s

t.stop() 在第 7 秒成功终止计时器(由 main 中的线程触发)。

关于C++ : Modifying a timer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30432614/

相关文章:

android - 以较长的间隔时间轮询数据库,哪种方法最好、最有效?

c++ - 限制模板化类数据类型

c++ - 内存泄漏——这怎么可能?

python - "AttributeError: ' 模块 ' object has no attribute ' argv '"使用 Python.h 时

C++ 窗体打开错误

python - wx.lib.pubsub : How to change the value in a timer

c++ - 轮廓 opencv : How to eliminate small contours in a binary image

linux - poll/epoll 兼容定时器

java - 如何从另一个场景JAVA取消定时器

python - Azure计时器触发函数 ".past_due"返回false