4

问题:如何在后台设置计时器?那就是创建计时器线程的线程在时钟滴答作响时仍然可以做其他事情。

尝试:-使用 _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 支持。

4

2 回答 2

1

我不确定你在这里有什么问题。您已经创建了一个永久更新成员变量的线程,timer并且您的主要用途是一个紧密/快速的循环,该循环(大概)打印该时间直到它达到 20。它没有做什么?从技术上讲,存在增加该值与在另一个线程中检查它的竞争条件,但就本示例而言,它应该没问题......

编辑: 尝试使用完全输入控制的非阻塞输入:

HANDLE hStdIn = GetStdHandle( STD_INPUT_HANDLE );
while ( true ) {
    if ( WAIT_OBJECT_0 == WaitForSingleObject( hStdIn, 1000 ) ) {
        // read input
        INPUT_RECORD inputRecord;
        DWORD events;
        if ( ReadConsoleInput( hStdIn, &inputRecord, 1, &events ) ) {
            if ( inputRecord.EventType == KEY_EVENT ) {
                printf( "got char %c %s\n",
                    inputRecord.Event.KeyEvent.uChar.AsciiChar,
                    inputRecord.Event.KeyEvent.bKeyDown ? "down" : "up" );
            }
        }
    }
    printf( "update clock\n" );
}
于 2012-11-19T16:19:38.620 回答
0

恐怕你误解了系统定时器是如何工作的以及如何使用它们——重点是它们会自动在后台运行,所以你不必自己进行线程管理。

这一般都有 Windows 计时器的示例和解释,如果您尝试推出自己的Timer课程,则可以使用它:Timers Tutorial

这是TimerWindows.NET自带的类,底部有代码示例:Timer Class

编辑添加:

这是适用于非 MFC 应用程序的 Win32 计时器示例版本(来自 turorial 页面):

int nTimerID;

void Begin(HWND hWindow_who_gets_the_tick)
{
    // create the timer to alert your window:
    nTimerID = SetTimer(hWindow_who_gets_the_tick, uElapse, NULL);
}

void Stop()
{
    // destroy the timer
    KillTimer(nTimerID);
}

有关详细信息,请参阅MSDN:定时器功能

然后在您的窗口过程中,您会收到WM_TIMER消息并根据需要进行响应。

或者,计时器可以调用用户定义的过程。有关详细信息,请参阅SetTimer 函数

于 2012-11-19T16:08:09.063 回答