Welcome, Guest
Username: Password: Remember me
CodeOcean Samples and DocFactory discussions and suggestions
  • Page:
  • 1

TOPIC:

multithreadingexample1 - high CPU usage 5 years 6 months ago #12795

  • Peter Heckert
  • Peter Heckert's Avatar Topic Author
  • Visitor
  • Visitor
Hi,
C:\codetyphon\CodeOcean\aa_LCLBasics\samples\multithreading\multithreadingexample1mw.pas

there is an endless busy-loop inside the thread, which causes high CPU usage.
The comment in **** is by me.
procedure TMyThread.Execute;
var
  newStatus : string;
begin
  fStatusText := 'TMyThread Starting ...';
  Synchronize(@Showstatus);
  fStatusText := 'TMyThread Running ...';
  while (not Terminated) and (true {any condition required}) do begin

    //******* sleep(xyz) is required here. CPU usage will go down from 30% to 0.xxxxx % **********************
    
    //here goes the code of the main thread loop
    newStatus:='TMyThread Time: '+FormatDateTime('YYYY-MM-DD HH:NN:SS',Now);
    
    if NewStatus <> fStatusText then begin
      fStatusText := newStatus;
      Synchronize(@Showstatus);
    end;
  end;
end;

So, as an example for learning this is helpful, but could irritate a beginner;

Please Log in or Create an account to join the conversation.

Last edit: by Peter Heckert.

multithreadingexample1 - high CPU usage 5 years 6 months ago #12812

  • Peter Heckert
  • Peter Heckert's Avatar Topic Author
  • Visitor
  • Visitor
Here is another question for this multithreading example:

The variable "MyThread" is allocated locally, that means it is allocated on the stack.
As soon as TForm1.FormCreate() exits, the stackframe is released and the variable "MyThread" is invalid.
The tread will access elements, which are stored in the body of this particular instance of the "TMyThread" class.
To my best knowledge, this is a bug.

Or isnt it?

procedure TForm1.FormCreate(Sender: TObject);
var
  MyThread : TMyThread;
begin
  MyThread := TMyThread.Create(True); // With the True parameter it doesn't start automatically
  if Assigned(MyThread.FatalException) then
    raise MyThread.FatalException;
      
  // Here the code initialises anything required before the threads starts executing

  MyThread.Start;
end;

(I have some aged experience with multithreading in C and decades ago with Borland Pascal and a commercial MT Library on DOS, but not with Object Pascal.)

Edit:

Oops, after reading the manual, I think I understand it.
A class variable actually is a reference (a hidden pointer) to an oject which is allocated on the heap. So this is probably not a bug.

Sorry, I am still learning and probably misleaded by some basic C++ knowledge... ;-)
However, the previous bug (busy loop) is true; it can be seen in the task manager.

Please Log in or Create an account to join the conversation.

Last edit: by Peter Heckert.
  • Page:
  • 1