if I’ve got a
While not terminated do
begin
doStuff;
end
loop in the execute method of a Delphi XE2 thread, and I want to not make it bogart all my flops.
What should I call,
in Delphi 7, it was easy, I’d call Sleep(X) where X was inversely proportional to how interesting I thought the thread was.
But now, I’ve got
SpinWait(X);
Which calls YieldProcessor X number of times
and
Yield;
which calls the windows function “SwitchToThread”.
Should I use any of these or should I just set the priority of the thread?
SpinWaitwastes time without giving up the processor. It’s likeSleep, but without yielding control to any other threads during the delay. If you don’t have multiple cores, then it’s a total waste because no other thread can do anything while you’re spinning. As far as I can tell,Yieldis analogous toSleep(0), except that if there is no other thread ready to run, then the calling thread just continues immediately.Neither of those sounds like what you want if you know that your thread really has nothing else to do.
The best solution would be to find or establish some waitable object (like a semaphore, event, or process handle) that you could wait to become signaled. Then you wouldn’t have to bother waking up at all, just so you can poll your status and go to sleep again.