[Lazarus] A few questions on threads

Michael Schnell mschnell at lumino.de
Tue Oct 4 12:14:14 CEST 2011


On 10/04/2011 11:37 AM, Frank Church wrote:
>
> What is the purpose of the while not Terminated in a threads execute loop?
> If a thread is doing its own thing and knows when or not it has 
> finished what is the purpose of the while not Terminated
In Lazarus (and Delphi), "Worker Threads" can't have an "Event Loop" and 
so "event driven programming" (using "On..." procedures for the user 
code) is not possible. That is why in a Thread the user needs to create 
the "Loop" himself. Such a Thread should always run to a stall in some 
blocking library functions, lest it will take 100 %  CPU time.
>
> Is Terminated designed to be called by other procedures besides the 
> thread itself? Can a thread be Terminated externally?
> This also seems to imply that if the code within the while not 
> Terminated loop is a long running sequence a Termniate command will 
> not be processed until control returns to the beginning of the loop
A thread should terminate itself by exiting the Execute procedure. If 
not "FreeOnTerminate" is set. after termination the main thread should 
free the TThread object.
>
> Can a thread respond to a new Execute command while it already Executing? 
No.
> Do threads have ways of being interrogated about their state while 
> Executing?
There are lots of ways of doing inter-thread communication. Simplest: 
any (no "ThreadVar") variable can  mutually be read and written. A good 
(portable) way of notifying the Main thread about a state change is 
"Application.QueueAsyncCall". "TThread.Synchronize" calls a main thread 
event while stalling the thread for some indefinite amount of time.
>
> Suspend and Resume have been deprecated, and I want to know how a 
> thread can be suspended.
Using Semaphores like "TCriticalSection".
>
> If a thread is not set to FreeOnTerminate, can a thread suspend itself 
> by using Terminate or some other custom function, doing some clean ups 
> and waiting so it can be restarted by the Start procedure, by adding 
> some custom fields to make it itself aware that it is an a paused 
> state, so that when an Execute is sent it look up those fields, set 
> Terminated to false and continue as though nothing has happened?
>
In certain applications (if it is not supposed to stall and wait) the 
main thread needs to check multiple times whether a TThread instance in 
fact is "Terminated" and thus can be freed.

-Michael




More information about the Lazarus mailing list