c++timerbackground

C++ background timer


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

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'.

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?

Thanks for your help in advance!


Solution

  • 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";
    }