在Delphi XE2的无限等待线程中调用哪种等待方法 [英] Which wait method to call in an infinite waiting thread for Delphi XE2

查看:60
本文介绍了在Delphi XE2的无限等待线程中调用哪种等待方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有

While not terminated do
begin
     doStuff;

end

在Delphi XE2线程的execute方法中循环,以及我不想让它成为我所有的失败者。

loop in the execute method of a Delphi XE2 thread, and I want to not make it bogart all my flops.

在Delphi 7中,我应该怎么称呼

What should I call,

很容易,我将其称为Sleep(X),其中X与我认为线程的有趣程度成反比。

in Delphi 7, it was easy, I'd call Sleep(X) where X was inversely proportional to how interesting I thought the thread was.

但是现在,我知道了

SpinWait(X);

哪个调用YieldProcessor X次数

Which calls YieldProcessor X number of times

Yield;

它会调用Windows函数 SwitchToThread。

which calls the windows function "SwitchToThread".

我应该使用其中的任何一个还是应该设置线程的优先级?

Should I use any of these or should I just set the priority of the thread?

推荐答案

SpinWait 浪费时间而没有放弃处理器。就像 Sleep ,但是在延迟期间没有将控制权交给其他任何线程。如果您没有多个核心,那将是一种浪费,因为在旋转时没有其他线程可以做任何事情。据我所知, Yield 类似于 Sleep(0),除非没有其他线程准备运行,然后调用线程将立即继续。

SpinWait wastes time without giving up the processor. It's like Sleep, 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, Yield is analogous to Sleep(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.

这篇关于在Delphi XE2的无限等待线程中调用哪种等待方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆