Saturday, July 7, 2012

threads in delphi

Threads in Delphi

threads in general definition In computer science, a thread of execution is the smallest unit of processing that can be scheduled by an operating system. A thread is a lightweight process. The implementation of threads and processes differs from one operating system to another, but in most cases, a thread is contained inside a process. Multiple threads can exist within the same process and share resources such as memory, while different processes do not share these resources. In particular, the threads of a process share the latter's instructions (its code) and its context (the values that its variables reference at any given moment).

On a single processor, multithreading generally occurs by time-division multiplexing (as in multitasking): the processor switches between different threads. This context switching generally happens frequently enough that the user perceives the threads or tasks as running at the same time. On a multiprocessor (including multi-core system), the threads or tasks will actually run at the same time, with each processor or core running a particular thread or task. 

Threads in Delphi In Delphi the thread as units in structrue , no more no less, but is the great importance of Thread is the way of it works, and the power provided to the application in the rapid completion of tasks and processes rather than relying on the main application's thread to do multiple tasks may Avoid him sag to apply and slow in processing. when creating new thread you will see this little code with new thread class(TFirstThread) derived from existing class called (TThread), with one overrided procedure called Excute where is the heart of Thread.
 
unit Unit1;

interface

uses
  Classes;

type
  TFirstThread = class(TThread)
  private
    { Private declarations }
  protected
    procedure Execute; override;
  end;

implementation


{ TFirstThread }

procedure TFirstThread.Execute;
begin
  { Place thread code here }
end;

end.

Thread has Many properties to control their behavior and mode of operation such as self-destruction, stop at the construction in this case you need a writing construction and destruction procedures, in the following way which is useful in case you creating special objects within the thread and destroyed at the completion of the thread
 
unit Unit1;

interface

uses
  Classes;

type
  TFirstThread = class(TThread)
  private
    { Private declarations }
  protected
    procedure Execute; override;
public
  constructor create ;
  destructor  destroy ; override ;
  end;

implementation


{ TFirstThread }

 constructor TFirstThread .create ;
begin
inherited Create(False); // False to run thread after creation


end ;

destructor  TFirstThread.destroy ;
begin

inherited ;
end;


procedure TFirstThread.Execute;
var i :integer ;
begin
  { Place thread code here }
for i:= 1 to 100 do
//Loop code here
 
end;

end.

to be continued