开发者

Why would I use Sleep() with infinite timeout?

开发者 https://www.devze.com 2022-12-14 05:37 出处:网络
According to MSDN, Sleep() can be provided INFINITE value and that \"indicates that the suspension should not t开发者_如何学运维ime out\".

According to MSDN, Sleep() can be provided INFINITE value and that "indicates that the suspension should not t开发者_如何学运维ime out".

Why would I want to call Sleep() with INFINITE timeout in my program?


I have used Sleep(INFINITE) and it makes perfect sense. I've used it to keep the thread alive. I have registered for WMI notification event (ExecNotificationQueryAsync, which receives event notification infinitely) then you need to keep the application alive. dont' know if this make sense to you.


A sleep with no timeout does not need a timer. This reduces the overhead where you anticipate a variable-length wait but are absolutely sure that the thread will be resumed.


As far as I know, Sleep, since they introduced SleepEx, it's just a thin, convenient wrapper around SleepEx, and when they rewrote it as a wrapper, they decided just to pass the timeout parameter to SleepEx, without processing it in any way. Obviously in this way the behavior of the function with INFINITE as timeout is propagated also to Sleep (and so must be documented), although, without the bAlertable parameter of the SleepEx, it's completely useless (a Sleep(timeout) is equal to SleepEx(timeout, FALSE), so you'll have an infinite nonalertable wait).

On Windows CE, then, they may have decided to change this behavior because it was actually silly, so I think that a Sleep(INFINITE) on CE is translated automatically to a SuspendThread; however, on Windows they are probably forced to keep the "simple" behavior for compatibility reasons.


In addition to what was said (basically waiting for an interrupt to happen) You might very well have an infinite timeout without being insane. For example, I've an application (a worker) that needs to do 3 different things at a time.

I chose to make each of those work run in new threads and have an infinite timeout in the Main() thread (as the program is not supposed to exit, except if an Exception is thrown in which case the whole app is restarted), for convenience and readability (I can comment out any of the 3 works without affecting the global behavior or easily split them to different workers if needed).

This probably adds a very small overhead compared to have 2 new thread + the main thread doing the 3rd work, but it's negligible considering today computers performances and memory.


There's no reasons one in his sane mind would ever Sleep(INFINITE). It has no practical meaning.

It is for generality and symmetry to WaitForSingleObject(..., timeout) and SleepEx(timeout), where INFINITE does make sense.

Reminding, that SleepEx will try to consume things out of your thread's APC queue.


Well, When we need to wait until ^C but we do not want while(1);

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号