c++ timer background

Temporizador de fondo C++



timer background (1)

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

Estoy intentando crear un temporizador en C ++ que se ejecutaría en segundo plano. Entonces, básicamente, si miras el ''bloque principal'', quiero ejecutar el temporizador (que va a contar hasta 0) y al mismo tiempo ejecutar el siguiente código, que en este caso es ''prueba''.

Como es ahora, la siguiente línea de código no se ejecutará hasta que el temporizador haya finalizado. ¿Cómo hago que el temporizador se ejecute en segundo plano?

¡Gracias por tu ayuda con anticipación!


C ++ 11. Debería funcionar con 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"; }

Si la operación realizada en el timer() lleva mucho tiempo, puede obtener una mayor precisión como esta:

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