问题:如何让计时器在后台滴答声?也就是创建计时器线程的线程可以在时钟滴答声的同时做其他事情。
尝试: -使用 _beginthreadex() --> 看起来有竞争条件。
尝试: -使用 _beginthreadex() --> 看起来有竞争条件。
class Timer{
...
static unsigned __stdcall tick(void *param){
while(1){
Timer::timer++;
Sleep(Timer::timer*1000);
}
return 1;
}
}
.....
HANDLE time_thread = (HANDLE) _beginthreadex(0, 0, &Timer::tick,0,0,NULL);
...
//test for 20 seconds
//want to do something while the clock is not 20 seconds
//the mainthread here still has to receive input
//What is the proper way to do it?
while (Timer::getTime() != 20){
cout << Timer::getTime()
}
CloseHandle(time_thread);
...
注意:我使用的是Visual Studio 2008,而不是11,因此我没有C++11支持。
GetStdHandle(STD_INPUT_HANDLE)
和WaitForSingleObject
,然后跳过线程。根据您要执行的操作,您可能还需要使用SetConsoleMode
。 - markWaitForSingleObject
函数等待标准输入句柄 1000 毫秒(1 秒)。每次从等待中返回时更新时钟并检查输入。 - mark