Timer to implement a time-out function

2019-02-20 07:00发布

I'm writing a Windows (Win32) program in C, which features a worker thread to process data from a USB hardware device. The thread handling all works well, however I now need to add a timer to handle a timeout function. I don't need a callback function, just the ability to start a single shot timer, and to be able to test weather it's complete without sleeping, something like this:

start_timout(1000);   // 1 second

while (timer_is_running())
{
  doing stuff while waiting...
  .
  .
  .
}

do stuff after timer is finished...
.
.
.

This would be running inside the worker thread.

I've looked at SetTimer(), and have tried creating a callback function that simply sets a global flag, then test for the flag, but that never gets set. I'm not sure if this is because I don't have a message handler inside my thread.

Any suggestions welcome.. Cheers!

2条回答
劫难
2楼-- · 2019-02-20 07:07

Thanks for your reply, I had something working quite quickly. Here's a distillation of my working code:

#include <windows.h>

static void func(void)
{
  HANDLE hTimer = NULL;
  LARGE_INTEGER liDueTime;

  liDueTime.QuadPart = -5000000LL;    // 0.5 seconds
  //liDueTime.QuadPart = -20000000LL;   // 2 seconds
  //liDueTime.QuadPart = -100000000LL;  // 10 seconds


  hTimer = CreateWaitableTimer(NULL, TRUE, NULL);


  SetWaitableTimer(hTimer, &liDueTime, 0, NULL, NULL, 0);

  while (WaitForSingleObject(hTimer, 0) == WAIT_TIMEOUT)
  {
    do stuff
  }
}

Regards, Toonie.

查看更多
放荡不羁爱自由
3楼-- · 2019-02-20 07:19

SetTimer requires you to catch the WM_TIMER event in a window and on top of that, is not very accurate. I wouldn't advise to use it.

Instead you could simply create another thread, let it do nothing but Sleep() for the specified time period (you could pass the time as parameter upon thread creation). You can then WaitForSingleObject(sleeper_thread, 0) to check if the timeout has elapsed.

查看更多
登录 后发表回答