Thread is writing on desktop - multithreading

I tried to make a runtime thread but the thread is behaving strangely, the code has no canvas reference.
procedure TBruteThread.Execute;
var
j: Integer;
begin
inherited;
FreeOnTerminate:=True;
for j:=1 to StrToInt(Form1.Edit1.Text) do begin
if Terminated then break;
Form1.Label2.Caption:=IntToStr(j);
end;
Form1.Label2.Caption:='Thread is destroyed';
Self.Terminate;
end;
Someone have any idea to solve this strange problem?

The problem with your code is that it is breaking the VCL threading rules. Access to VCL components must be made from the main thread. Use Synchronise or Queue (methods of TThread) to execute GUI updates on the main thread.
Other comments:
Set FreeOnTerminate outside the thread method.
Calling Terminate as the final act of the thread method is pointless. The thread is just about to terminate.

Related

Thread Error : Handle Not Valid (6) Delphi XE7 [duplicate]

In a given example I am receiving an exception when calling AThread.Free.
program Project44;
{$APPTYPE CONSOLE}
uses
SysUtils, Classes, Windows;
type
TMyException = class(Exception);
var
AThread: TThread;
begin
AThread := TThread.Create(True);
try
AThread.FreeOnTerminate := True;
//I want to do some things here before starting the thread
//During the setup phase some exception might occur, this exception is for simulating purpouses
raise TMyException.Create('exception');
except
AThread.Free; //Another exception here
end;
end.
I have two questions:
How should I free AThread instance of TThread in a given example?
I don't understand, why TThread.Destroy is calling Resume before destroing itself. What is the point of this?
You can't set FreeOnTerminate to True and call Free on the thread instance. You have to do one or the other, but not both. As it stands your code destroys the thread twice. You must never destroy an object twice and of course when the destructor runs for the second time, errors occur.
What happens here is that since you created the thread suspended, nothing happens until you explicitly free the thread. When you do that the destructor resumes the thread, waits for it to complete. This then results in Free being called again because you set FreeOnTerminate to True. This second call to Free closes the handle. Then you return to the thread proc and that calls ExitThread. This fails because the thread's handle has been closed.
As Martin points out in the comment you must not create TThread directly since the TThread.Execute method is abstract. Also, you should not use Resume which is deprecated. Use Start to begin execution of a suspended thread.
Personally I don't like to use FreeOnTerminate. Using this feature results in the thread being destroyed on a different thread from which it was created. You typically use it when you want to forget about the instance reference. That then leaves you uncertain as to whether or not the thread has been destroyed when your process terminates, or even whether it is terminating and freeing itself during process termination.
If you must use FreeOnTerminate then you need to make sure that you don't call Free after having set FreeOnTerminate to True. So the obvious solution is to set FreeOnTerminate to True immediately before after calling Start and then forget about the thread instance. If you have any exceptions before you are ready to start then you can safely free the thread then since you FreeOnTerminate would still be False at that point.
Thread := TMyThread.Create(True);
Try
//initialise thread object
Except
Thread.Free;
raise;
End;
Thread.FreeOnTerminate := True;
Thread.Start;
Thread := nil;
A more elegant approach would be to move all the initialisation into the TMyThread constructor. Then the code would look like this:
Thread := TMyThread.Create(True);
Thread.FreeOnTerminate := True;
Thread.Start;
Thread := nil;
The situation is very complicated in your case.
First, you does not actually free a suspended thread; a thread is resumed in destructor:
begin
Terminate;
if FCreateSuspended then
Resume;
WaitFor;
end;
Since Terminate is called before Resume, the Execute method never runs, and thread terminates immediately after being resumed:
try
if not Thread.Terminated then
try
Thread.Execute;
except
Thread.FFatalException := AcquireExceptionObject;
end;
finally
Result := Thread.FReturnValue;
FreeThread := Thread.FFreeOnTerminate;
Thread.DoTerminate;
Thread.FFinished := True;
SignalSyncEvent;
if FreeThread then Thread.Free;
Now look at the last line - you call destructor (Thread.Free) from destructor itself!
Fantastic bug!
To answer your questions:
You just can't use FreeOnTerminate:= True in your code;
You should ask Embarcadero why TThread is designed so; my guess - some code
(DoTerminate method) should be executed in thread context while
thread terminates.
You can send a feature request to QC: add FFreeOnTerminate:= False to TThread.Destroy implementation:
destructor TThread.Destroy;
begin
FFreeOnTerminate:= False;
// everything else is the same
..
end;
That should prevent recursive desctructor call and make your code valid.

Do I have to signal an anonymous thread to exit if the main thread is done? [duplicate]

This question already has answers here:
Is it necessary to explicitly stop all threads prior to exiting a Win32 application?
(5 answers)
Closed 8 years ago.
Suppose I have an anonymous thread that does some background processing:
procedure TForm1.FormCreate(Sender: TObject);
begin
TThread.CreateAnonymousThread(procedure begin
while True do begin
Sleep(500);
OutputDebugString('I am alive');
end;
end).Start;
end;
The thread doesn't share any ressources with the main thread, it just sits there and runs "forever".
Since there is no built-in mechanism like Terminate for anonymous threads, does that mean that I don't have to notify the thread when the main thread of the process exits?
If you just fire up a fresh VCL application an paste the code from above in the FormCreate event it will write I am alive every half second to the debug messages. When the application exits (i. e. by closing the form), it seems that the thread is also exited, despite the fact that it doesn't check for any signal.
Is that ok, or do I have to implement some signal using TEvent or similar to notify the thread?
Or is it better to write a custom TThread descendent and keep a reference to the thread to Thread.Free it later?
You need to terminate any thread you create, even an anonymous thread, eg:
procedure TForm1.FormCreate(Sender: TObject);
begin
TThread.CreateAnonymousThread(procedure begin
while not Application.Terminated do begin // <--
Sleep(500);
OutputDebugString('I am alive');
end;
end).Start;
end;

Synchronize appears to hang thread

I have a message queue based on a thread that processes messages being thrown at it. As some activities in the thread may be VCL commands they are performed in Synchronize. As soon Synchronize is called the thread hangs. Sample code:
TMessageQ = class (TThread)
...
procedure TMessageQ.do_msg;
begin
case CurrentMessage.Command of
cQSize: if Assigned (OnSize) then OnSize (CurrentMessage);
cQReady: if Assigned (OnReady) then OnReady (CurrentMessage);
end; // case
end; // do_msg /
procedure TMessageQ.doTask (Sender: TObject);
begin
while FQ.Count > 0 do
begin
FSection.Enter;
try
CurrentMessage := FQ.Dequeue;
finally
FSection.Leave;
end; // try..finally
Synchronize (do_msg);
end; // while
end; // doTask //
No statement in do_msg is ever being processed. Does somebody know what I am doing wrong?
TThread.Synchronize() blocks until the main thread processes the request. The main thread requires an active message loop in order to process requests (unless you manually call Application.ProcessMessages() or CheckSynchronize() periodically). If your thread's main work is always being invoked by TThread.Synchronize(), there is no point in using a thread at all. You could just use a timer or custom window message in the main thread instead and take out all of the unnecessary complexity.

TThread.Execute is not called as expected

I am trying to display an activity indicating overlay (a spinning circle of dots) during a lengthy operation in my application. For this, i created a borderless transparent form with a TImage and an Imagelist, which i sought to update in a thread during the time the main thread is busy.
The problem i encountered is that the lengthy operation does not seem to get 'interupted' by my thread. The thread.Execute function loops a few times before the lengthy operation starts, and then again when the operation is finished.
It seems as if the thread is starved for some reason. I tried to raise it's priority, but could not see any effect.
Does anyone have similar experiences to share, or maybe even a solution?
Source code of thread function
procedure TIndicatorThread.Execute;
begin
inherited;
while(not Terminated) do
begin
fDlg.fCurindex := (fDlg.fCurindex+1) mod 12;
Synchronize(UpdateImage);
Application.ProcessMessages;
sleep(80);
end;
Synchronize(fDlg.close);
Synchronize(fDlg.Free);
end;
main thread
begin
[...]
myThread := TIndicatorThread.Create;
mythread.Resume;
Init_SomeUIRelatedstuff;
Application.ProcessMessages;
DoLengthyOperation;
mythread.Terminate;
Your are doing the bulk of your thread work inside of Synchronize(), which delegates the work back to the main thread. If the main thread's lengthy operation is not processing new messages from the message queue, then Synchronize() has to wait. That is why your thread does not do anything while the lengthy operation is running.
Your code is a poor example of how to use a thread effectively. What you should have done instead is perform the lengthy operation itself in the thread, and let the main thread handle the UI updates while the thread is running, eg:
procedure TWorkThread.Execute;
begin
DoLengthyOperation;
end;
begin
...
Init_SomeUIRelatedstuff;
Application.ProcessMessages;
myThread := TWorkThread.Create(False);
while WaitForSingleObject(myThread.Handle, 80) = WAIT_TIMEOUT do
begin
fDlg.fCurindex := (fDlg.fCurindex+1) mod 12;
UpdateImage;
Application.ProcessMessages;
end;
mythread.Free;
fDlg.Close;
fDlg.Free;
...
end;
I used GIF image component that can show animated GIFs (http://www.tolderlund.eu/delphi/),
and I put a lengthy operation inside a timer (which
executes in separate thread).
Simple but effective.

Free a TThread either automatically or manually

I have a main thread and a separate thread in my program. If the separate thread finishes before the main thread, it should free itself automatically. If the main thread finishes first, it should free the separate thread.
I know about FreeOnTerminate, and I've read that you have to be careful using it.
My question is, is the following code correct?
procedure TMyThread.Execute;
begin
... Do some processing
Synchronize(ThreadFinished);
if Terminated then exit;
FreeOnTerminate := true;
end;
procedure TMyThread.ThreadFinished;
begin
MainForm.MyThreadReady := true;
end;
procedure TMainForm.Create;
begin
MyThreadReady := false;
MyThread := TMyThread.Create(false);
end;
procedure TMainForm.Close;
begin
if not MyThreadReady then
begin
MyThread.Terminate;
MyThread.WaitFor;
MyThread.Free;
end;
end;
You can simplify this to:
procedure TMyThread.Execute;
begin
// ... Do some processing
end;
procedure TMainForm.Create;
begin
MyThread := TMyThread.Create(false);
end;
procedure TMainForm.Close;
begin
if Assigned(MyThread) then
MyThread.Terminate;
MyThread.Free;
end;
Explanation:
Either use FreeOnTerminate or free the thread manually, but never do both. The asynchronous nature of the thread execution means that you run a risk of not freeing the thread or (much worse) doing it twice. There is no risk in keeping the thread object around after it has finished the execution, and there is no risk in calling Terminate() on a thread that has already finished either.
There is no need to synchronize access to a boolean that is only written from one thread and read from another. In the worst case you get the wrong value, but due to the asynchronous execution that is a spurious effect anyway. Synchronization is only necessary for data that can not be read or written to atomically. And if you need to synchronize, don't use Synchronize() for it.
There is no need to have a variable similar to MyThreadReady, as you can use WaitForSingleObject() to interrogate the state of a thread. Pass MyThread.Handle as the first and 0 as the second parameter to it, and check whether the result is WAIT_OBJECT_0 - if so your thread has finished execution.
BTW: Don't use the OnClose event, use OnDestroy instead. The former isn't necessarily called, in which case your thread would maybe continue to run and keep your process alive.
Have the main thread assign a handler to the worker thread's OnTerminate event. If the worker thread finishes first, then the handler can signal the main thread to free the thread. If the main thread finishes first, it can terminate the worker thread. For example:
procedure TMyThread.Execute;
begin
... Do some processing ...
end;
procedure TMainForm.Create;
begin
MyThread := TMyThread.Create(True);
MyThread.OnTerminate := ThreadFinished;
MyThread.Resume; // or MyThread.Start; in D2010+
end;
const
APPWM_FREE_THREAD = WM_APP+1;
procedure TMainForm.ThreadFinished(Sender: TObject);
begin
PostMessage(Handle, APPWM_FREE_THREAD, 0, 0);
end;
procedure TMainForm.WndProc(var Message: TMessage);
begin
if Message.Msg = APPWM_FREE_THREAD then
StopWorkerThread
else
inherited;
end;
procedure TMainForm.StopWorkerThread;
begin
if MyThread <> nil then
begin
MyThread.Terminate;
MyThread.WaitFor;
FreeAndNil(MyThread);
end;
end;
procedure TMainForm.Close;
begin
StopWorkerThread;
end;
No, your code is not good (though it probably will work in 99.99% or even 100% cases). If you are planning to terminate work thread from main thread, don't set FreeOnTerminate to True (I don't see what are you trying to gain in the above code by setting FreeOnTerminate to True, it at least makes your code less understandable).
A more important situation with terminating work threads is that you are trying to close an application while work thread is in wait state. The thread will not be awaken if you just call Terminate, generally you should use additional syncronization object (usually event) to wake up the work thread.
And one more remark - there is no need for
begin
MyThread.Terminate;
MyThread.WaitFor;
MyThread.Free;
end;
if you look at TThread.Destroy code, it calls Terminate and WaitFor, so
MyThread.Free;
is enough (at least in Delphi 2009, have no Delphi 7 sources at hand to check).
Updated
Read mghie answer. Consider the following situation (better on 1 CPU system):
main thread is executing
procedure TMainForm.Close;
begin
if not MyThreadReady then
begin
MyThread.Terminate;
MyThread.WaitFor;
MyThread.Free;
end;
end;
it checked MyThreadReady value (it is False) and was switched off by scheduler.
Now scheduler switches to work thread; it executes
Synchronize(ThreadFinished);
and forces scheduler to switch back to main thread. Main thread continues execution:
MyThread.Terminate; // no problem
MyThread.WaitFor; // ???
MyThread.Free;
can you say what will happen at WaitFor? I can't (requires a deeper look into TThread sources to answer, but at first glance looks like a deadlock).
Your real error is something different - you have written an unreliable code and trying to find out is it correct or not. That is bad practice with threads - you should learn to write a reliable code instead.
As for resources - when the TThread (with FreeOnTerminate = False) is terminated the only resources that remains allocated is Windows thread handle (it does not use substantial Windows resources after thread is terminated) and Delphi TThread object in memory. Not a big cost to be on the safe side.
Honestly, your
... Do some processing
Is the real problem here. Is that a loop for doing something recursively? If not and, instead, thats a huge task, you should consider split this task in small procedures / functions, and put all together in the execute body, calling one after another with conditional if's to know the thread state, like:
While not Terminated do
begin
if MyThreadReady then
DoStepOneToTaskCompletion
else
clean_and_or_rollback(Something Initialized?);
if MyThreadReady then
DoStepTwoToTaskCompletion
else
clean_and_or_rollback(Something Initialized?, StepOne);
if MyThreadReady then
DoStepThreeToTaskCompletion
else
clean_and_or_rollback(Something Initialized?, StepOne, StepTwo);
Self.DoTerminate; // Not sure what to expect from that one
end;
It is dirty, almost a hack, but will work as expected.
About FreeOnTerminate, well... just remove the declaration and always
FreeAndNil(ThreadObject);
I'm not a fan of syncronise. I like more critical sections, for the flexibility to extend the code to handle more shared data.
On the form public section, declare:
ControlSection : TRTLCriticalSection;
On form create or somewhere else before thread.create ,
InitializeCriticalSection(ControlSection);
Then, every time you write to a shared resource (including your MyThreadReady variable), do
EnterCriticalSection ( ControlSection );
MyThreadReady := True; //or false, or whatever else
LeaveCriticalSection ( ControlSection );
Before you go (exit), call
DeleteCriticalSection ( ControlSection );
and free your thread as you always do.
Regards
Rafael
I would state that mixing models is simply not recommended. You either use FreeOnTerminate and never touch the thread again, or you don't. Otherwise, you need a protected way for the two to communicate.
Since you want fine control over the thread variable, then don't use FreeOnTerminate. If your thread finishes early, clear the local resources that the thread has consumed as you normally would, and then simply let the main thread free the child thread when the application is finished. You'll get the best of both worlds - resources freed by the child thread as soon as it can be, and no worries about thread synchronization. (And it's got the added bonus of being much simpler in design/code/understanding/support...)

Resources