Alternative to sleeping inside the thread

Various answers suggest that it’s good to sleep inside the stream, for example: Avoid sleep . Why exactly? One of the reasons why it is often given is that it is difficult to gracefully exit the stream (signaling its cessation) if it is sleeping.

Let's say I wanted to periodically check for new files in a network folder, perhaps every 10 seconds. This seems ideal for a stream with a priority set to low (or lowest), because I don't want the potentially lengthy file I / O process to affect my main stream.

What are the alternatives? The code is specified in Delphi, but applies equally to any multi-threaded application:

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; 

Minor modification possible:

 // Rest a little before spinning around again nSleepCounter := 0; while (not Terminated) and (nSleepCounter < 500) do begin Sleep(TwentyMilliseconds); Inc(nSleepCounter); end; 

but it is still related to ...

+6
source share
2 answers

The standard way to do this is to wait for a cancel event. In pseudo code, which looks like this:

 while not Terminated do begin // Check for new files // ... // Rest a little before spinning around again FTerminationEvent.WaitFor(TenSeconds); end; 

To exit, you can override TerminatedSet :

 procedure TMyThread.TerminatedSet; begin inherited; FTerminationEvent.SetEvent; // abandon the wait in the thread method end; 

Waiting for an event either expires or stops because the event is signaled. This allows your thread to temporarily pause and not load the processor, but also respond to termination requests.

+8
source

If this was my job, I think I would solve it with a wrapper class with TTimer in it, creating a new thread every 10 seconds.

The appearance of a new thread is somewhat expensive, but if this is what you do only every 10 seconds, I think the performance that falls into the main thread is negligible.

Steps:

  • Create a wrapper class, TMyFileSearcher.
  • Let it contain a TTimer.
  • Each time the timer runs, a new stream is created and a file search is performed.
  • Add an OnTerminate handler to TMyFileSearcher to handle returned files.

There would also be some other considerations, such as keeping track of whether a thread was spawned so that you would not create a new thread while the old one is running.

But other than that, I think it should be pretty simple to implement.

+1
source

All Articles