各种答案表明睡在线程中是一个坏主意,例如:避免睡眠.为什么呢?经常给出的一个原因是,如果正在休眠,很难优雅地退出线程(通过发信号通知它终止).
假设我想定期检查网络文件夹中的新文件,可能每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;
Run Code Online (Sandbox Code Playgroud)
一个小修改可能是:
// Rest a little before spinning around again
nSleepCounter := 0;
while (not Terminated) and (nSleepCounter < 500) do
begin
Sleep(TwentyMilliseconds);
Inc(nSleepCounter);
end;
Run Code Online (Sandbox Code Playgroud)
但这仍然涉及睡眠......
我有一个基类TThread,它有像TThreadSockandTThreadPool这样的子类,它覆盖了该.Terminate()方法。这些孩子的孩子(如TThreadSockDownload或TThreadPoolCollect)继承了这些.Terminate()方法(甚至可能覆盖它们):
type
TThreadSock= class( TThread )
procedure Terminate; // Hides TThread.Terminate
end;
TThreadSockDownload= class( TThreadSock );
TThreadSockUpload= class( TThreadSock )
procedure Terminate; // Hides TThreadSock.Terminate
end;
TThreadPool= class( TThread )
procedure Terminate; // Hides TThread.Terminate
end;
TThreadPoolCollect= class( TThreadPool );
Run Code Online (Sandbox Code Playgroud)
我的问题是:我有一个可以包含所有内容的列表,所以最常见的分母是TThread. 从那个基类我需要调用最“幼稚”的.Terminate()方法。目前我的方法是这样的:
var
oThread: TThread;
begin
oThread:= GetNextThread();
if oThread is TThreadSockDownload then TThreadSockDownload(oThread).Terminate() else
if oThread is TThreadSockUpload then TThreadSockUpload(oThread).Terminate() else …Run Code Online (Sandbox Code Playgroud)