【发布时间】:2016-03-01 20:19:30
【问题描述】:
各种答案表明在线程中休眠是一个坏主意,例如:Avoid sleep。为什么?经常给出的一个原因是,如果线程处于休眠状态,则很难优雅地退出线程(通过发出终止信号)。
假设我想定期检查网络文件夹中的新文件,可能每 10 秒检查一次。这对于优先级设置为低(或最低)的线程来说似乎是完美的,因为我不希望潜在的耗时文件 I/O 影响我的主线程。
有哪些选择?代码在 Delphi 中给出,但同样适用于任何多线程应用程序:
procedure TNetFilesThrd.Execute();
begin
try
while (not Terminated) do
begin
// Check for new files
// ...
// Rest a little before spinning around again
if (not Terminated) then
Sleep(TenSeconds);
end;
finally
// Terminated (or exception) so free all resources...
end;
end;
一个小的修改可能是:
// Rest a little before spinning around again
nSleepCounter := 0;
while (not Terminated) and (nSleepCounter < 500) do
begin
Sleep(TwentyMilliseconds);
Inc(nSleepCounter);
end;
但这仍然涉及睡眠...
【问题讨论】:
-
在一个线程中休眠也可能很危险,并且在使用多线程时会导致未定义的行为。
-
更好的选择是等待信号事件相同的超时时间;如果事件发出信号,则立即退出线程,如果超时,则留在
while循环中。 -
@ITguy 睡觉没有内在的危险,也不会导致未定义的行为
-
解决方案在 C# 和 C++ 中会完全不同,在 C++ 中它甚至可能不在 Windows 上,这个问题在 C# 和 C++ 中被标记是愚蠢的。编辑问题。阿兰,让你的问题笼统是愚蠢的。同样愚蠢的问题可能是,我该如何做晚餐。 (说明应该适用于任何晚餐。)
-
@Warren 通用问题很好。答案在任何地方都是一样的。
标签: c# c++ multithreading delphi