1

I need to wait some time in one of my threads, I started to think about WaitForSingleObject but it needs handles to wait on, although it can take a timeout input;

Another resolution may use SetTimer but it seems that it will create WM_TIMER message but I don't have change to catch that message since I am in a thread, so is there something I can use here ? can I use Sleep?

Tudor
  • 58,972
  • 12
  • 89
  • 138
Zhi Wang
  • 1,018
  • 2
  • 16
  • 32
  • 1
    Please edit your question to include which platform and language you're using. I *suspect* it's C++ and Win32, but you should be explicit. – Jon Skeet Sep 19 '12 at 05:59

4 Answers4

3

WM_TIMER is not very reliable. It's a low priority windows message and it isn't sent if the user is resizing the window (for example).

I would say "Sleep" is the best option, but in the past I have used WaitForSingleObject because it allows me to pass in a handle to Cancel the wait operation if I need to. Depends on your design.

akhisp
  • 675
  • 3
  • 5
2

The proper method strongly depends on what you mean with to wait some time. The Sleep function and the WaitForSingleObject function are basically of the same accuracy. Depending on the underlaying hardware and the version of the OS minimum delays achievable are in the range of 0 .. 1 .. 20ms. If you desire to just wait for seconds or 10th of seconds these two functions are the right choice.

Waiting for shorter periods in time i.e. in the millisecond range needs more detailed investigation. See this or this answer for more details.

Community
  • 1
  • 1
Arno
  • 4,664
  • 3
  • 31
  • 56
1

If you just want to make the thread wait for a fixed amount of time, use Sleep() for that. But if you want the wait to be interruptable by some external operation, you have to wait on something, whether that be a timer (see SetTimer() and Get/PeekMessage()), an event (see CreateEvent() and WaitForSingleObject()), a message in the thread's queue (see PostThreadMessage() and MsgWaitForMultipleObjects()), an I/O Completion Port callback (see PostQueuedCompletionStatus() and GetQueuedCompletionStatus()), etc.

Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620
0

If you want to block a thread and wait until a specific time, you can use the CreateWaitableTimer() function, and then use WaitForSingleObject() on the timer handle.

This function can also wait for a specific period and with WaitForMultipleObjects() will let you block until the timer interval AND other objects at the same time.

Deanna
  • 22,939
  • 7
  • 65
  • 142