C ++背景定时器 [英] C++ background timer

查看:127
本文介绍了C ++背景定时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <time.h>

using namespace std;
using namespace System;

void wait ( int seconds )
{
  clock_t endwait;
  endwait = clock() + seconds * CLOCKS_PER_SEC ;
  while (clock() < endwait) {}
}
void timer()
{
    int n;
    printf ("Start\n");
    for (n=10; n>0; n--) // n = time
    {
        cout << n << endl;
        wait (1); // interval (in seconds).
    }
    printf ("DONE.\n");
    system("PAUSE");
}
int main ()
{
    timer();
    cout << "test" << endl; // run rest of code here.}

  return 0;
}

我试图创建C ++中的定时器,会在后台运行。所以基本上,如果你想看看主块我要运行的定时器(将要下降到0计数),并在同一时间运行的下一个code,在这种情况下是测试 。

I'm trying to create a timer in C++ which would run in the background. So basically if you'd look at the 'main block' I want to run the timer (which is going to count down to 0) and at the same time run the next code, which in this case is 'test'.

由于它现在是code的下一行不会被运行,直到定时器已经完成了。如何让我在后台定时器的运行?

As it is now the next line of code won't be run until the timer has finished. How do I make the timer run in the background?

感谢您的帮助提前!

推荐答案

C ++ 11。应与VS11测试工作。

C++11. Should work with VS11 beta.

#include <chrono>
#include <iostream>
#include <future>

void timer() {
    std::cout << "Start\n";
    for(int i=0;i<10;++i)
    {
        std::cout << (10-i) << '\n';
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    std::cout << "DONE\n";
}
int main ()
{
    auto future = std::async(timer);
    std::cout << "test\n";
}

如果定时器()在执行的操作需要显著的时间,你可以得到这样更好的精度:

If the operation performed in timer() takes significant time you can get better accuracy like this:

void timer() {
    std::cout << "Start\n";
    auto start = std::chrono::high_resolution_clock::now();
    for(int i=0;i<10;++i)
    {
        std::cout << (10-i) << '\n';
        std::this_thread::sleep_until(start + (i+1)*std::chrono::seconds(1));
    }
    std::cout << "DONE\n";
}

这篇关于C ++背景定时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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