#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),同时运行下一个代码,在本例中为“测试”。
现在,在计时器完成之前,下一行代码不会运行。如何让计时器在后台运行?
提前感谢您的帮助!
C++11。应该与 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";
}
如果操作执行于timer()
花费大量时间你可以获得更好的准确性,如下所示:
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";
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)