Correct thread terminate and destroy
http://www.techques.com/question/1-3788743/Correct-thread-destroy
Hello At my form I create TFrame at runtime.
At this frame I create background thread with executes commands in endless loop.
But when I destroy this frame I should destroy this thread. I try
thread.Suspend;
thread.Terminate;
FreeAndNil(thread);
but get AV and ThreadError. How should i destroy thread?
Don't suspend the thread. The terminate method just set the Terminated property to true,
and your Execute method is responsible to terminate the thread.
If it is suspended, it will not get a chance to terminate.
Another problem with the code above, is that it likely frees the thread
before it has a change to terminate the normal way.
You must make sure that thread exits it's execute method to terminate it properly.
Code could be something like this:
procedure TThread.Execute;
begin
while not Self.Terminated do
begin
//do something
end;
end;
Call this when You want to destroy thread:
thread.Terminate;
thread.WaitFor;
FreeAndNil(thread);
It's not necessary to call `Terminate` and `WaitFor` from the outside,
as the thread destructor will do it itself.
It may be necessary though to call it from overwritten destructors,
before any fields are freed, to make sure these are no longer used from the thread.
It is sufficient to do thread.Terminate
.
But you will probably want to set thread.FreeOnTerminate := true
when it is created.
Of course, in the tight loop of your thread (that is, in Execute
),
you need to check if the thread has been requested to terminate
(check the Terminated
property).
If you find that the thread has been requested to terminate,
simply break from the loop and exit from Execute
.
thread.Terminate only sets FTerminated property to True. It doesn't destroy thread.
I know. But every thread must check for that in its Execute method.
I assume the OP is doing this.
You should never call suspend on a tthread its not safe to do so and resume should only be used to start a thread that was created suspended.
In Delphi 2010 the suspend and resume where depreciated and the method start was introduced to reinforce this.
For a more complete explanation see this thread at Codegears forums.
having said that there are 2 ways I will terminate and free a tthread.
1: I Set FreeOnTerminate when the thread is created so I just call.
Thread.Terminate;
2: Free the thread explicitly, as I need to read a result from a public property before the thread is freed and after it has terminated.
Thread.Terminate;
Thread.WaitFor;
//Do somthing like read a public property from thread object
if Thread <> nil then FreeAndNil(Thread);
In the main execute loop it may be a good idea to put some exception handling in.
Or you may be left wondering why the thread appears to terminate its self.
This may be causing the AV if the thread is set to FreeOnTerminate and it has already been freed when you try to free it.
procedure TThread.Execute;
begin
while not Terminated do
begin
try
//do something
except
on E:Exception do
//handle the exception
end;
end;
end;
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;
Thanks!
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 callingTerminate()
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 atomi
How to terminate anonymous threads in Delphi on application close?
I have a Delphi application which spawns 6 anonymous threads upon some TTimer.OnTimer event.
If I close the application from the X button in titlebar Access Violation at address $C0000005 is raised and FastMM reports leaked TAnonymousThread objects.
Which is the best way to free anonymous threads in Delphi created within OnTimer event with TThread.CreateAnonymousThread() method?
SOLUTION which worked for me:
Created a wrapper of the anonymous threads which terminates them upon being Free-ed.
type
TAnonumousThreadPool = class sealed(TObject)
strict private
FThreadList: TThreadList;
procedure TerminateRunningThreads;
procedure AnonumousThreadTerminate(Sender: TObject);
public
destructor Destroy; override; final;
procedure Start(const Procs: array of TProc);
end; { TAnonumousThreadPool } procedure TAnonumousThreadPool.Start(const Procs: array of TProc);
var
T: TThread;
n: Integer;
begin
TerminateRunningThreads; FThreadList := TThreadList.Create;
FThreadList.Duplicates := TDuplicates.dupError; for n := Low(Procs) to High(Procs) do
begin
T := TThread.CreateAnonymousThread(Procs[n]);
TThread.NameThreadForDebugging(AnsiString('Test thread N:' + IntToStr(n) + ' TID:'), T.ThreadID);
T.OnTerminate := AnonumousThreadTerminate;
T.FreeOnTerminate := true;
FThreadList.LockList;
try
FThreadList.Add(T);
finally
FThreadList.UnlockList;
end;
T.Start;
end;
end; procedure TAnonumousThreadPool.AnonumousThreadTerminate(Sender: TObject);
begin
FThreadList.LockList;
try
FThreadList.Remove((Sender as TThread));
finally
FThreadList.UnlockList;
end;
end; procedure TAnonumousThreadPool.TerminateRunningThreads;
var
L: TList;
T: TThread;
begin
if not Assigned(FThreadList) then
Exit;
L := FThreadList.LockList;
try
while L.Count > do
begin
T := TThread(L[]);
T.OnTerminate := nil;
L.Remove(L[]);
T.FreeOnTerminate := False;
T.Terminate;
T.Free;
end;
finally
FThreadList.UnlockList;
end;
FThreadList.Free;
end; destructor TAnonumousThreadPool.Destroy;
begin
TerminateRunningThreads;
inherited;
end;
End here is how you can call it:
procedure TForm1.Button1Click(Sender: TObject);
begin
FAnonymousThreadPool.Start([ // array of procedures to execute
procedure{anonymous1}()
var
Http: THttpClient;
begin
Http := THttpClient.Create;
try
Http.CancelledCallback := function: Boolean
begin
Result := TThread.CurrentThread.CheckTerminated;
end;
Http.GetFile('http://mtgstudio.com/Screenshots/shot1.png', 'c:\1.jpg');
finally
Http.Free;
end;
end, procedure{anonymous2}()
var
Http: THttpClient;
begin
Http := THttpClient.Create;
try
Http.CancelledCallback := function: Boolean
begin
Result := TThread.CurrentThread.CheckTerminated;
end;
Http.GetFile('http://mtgstudio.com/Screenshots/shot2.png', 'c:\2.jpg');
finally
Http.Free;
end;
end
]);
end;
No memory leaks, proper shutdown and easy to use.
If you want to maintain and exert control over your threads' lifetimes then you should not use anonymous threads.
Maintain a list of TThread instances and free them at shutdown time.
Whilst it is possible to do what you want with anonymous threads,
it's a lot of extra work that brings no real benefits.
I see.
But I still do not get it.
TAnonymousThread is a descendant of TThread.
So I can maintain a list of them and try to terminate them (since the RTL does not do it automatically).
When I try to terminate it says:
Project mtgstudio.exe raised exception class EThread with message 'Thread Error: The handle is invalid (6)'.
Read the docs for the anonymous thread.
You are not allowed to hold a reference to the TThread since it uses FreeOnTerminate.
System.Classes.TThread.CreateAnonymousThread
Creates an instance of an internally derived thread.
CreateAnonymousThread creates an instance of an internally derived TThread that simply will call the anonymous method of typeTProc.
This thread is created as suspended, so you should call the Start method to make the thread run.
The thread is also marked as FreeOnTerminate, so you should not touch the returned instance after calling Start.
It is possible that the instance had run and then has been freed before other external calls or operations on the instance were attempted.
type TProc = reference to procedure;
type TProc = reference to procedure(Arg1: T);
type TProc = reference to procedure(Arg1: T1, Arg2: T2);
type TProc = reference to procedure(Arg1: T1, Arg2: T2, Arg3: T3);
type TProc = reference to procedure(Arg1: T1, Arg2: T2, Arg3: T3, Arg4: T4);
TProc declares a reference to a generic procedure.
Use the TProc type as a reference to a generic procedure.
There are a few variants of TProc type, each accepting a different number of generic arguments.
Correct thread terminate and destroy的更多相关文章
- std::thread “terminate called without an active exception”
最近在使用std::thread的时候,遇到这样一个问题: std::thread t(func); 如果不使用调用t.join()就会遇到 "terminate called whitho ...
- The CLR's Thread Pool
We were unable to locate this content in zh-cn. Here is the same content in en-us. .NET The CLR's Th ...
- delphi.thread.同步
注意:此文只是讲线程间的同步,其它同步不涉及. 线程同步是个好话题,因为写线程经常会遇到,所以就写写自己知道的东西. D里面,同步(特指线程同步)从线程的角度来分,有几种情况: 1:主线程与工作线程的 ...
- JDWP Agent
JDWP Agent Implementation Description Revision History Disclaimer 1. About this Document 1.1 Purpose ...
- Tun/Tap interface tutorial
Foreword: please note that the code available here is only for demonstration purposes. If you want t ...
- Window Linux下实现指定目录内文件变更的监控方法
转自:http://qbaok.blog.163.com/blog/static/10129265201112302014782/ 对于监控指定目录内文件变更,window 系统提供了两个未公开API ...
- loadrunner监控度量项及中文解释
1. Number of Concurrent Users (NCU) 并发用户数 – 在指定时刻,系统观察到的并发用户连接数. 2. Request Per Second (RPS) 每秒处理请求数 ...
- Code Review Checklist
左按:当年需要一份详细的代码评审清单作参考,翻译了此文. 版权声明:本文为博主原创文章,未经博主允许不得转载. 目录(?)[-] General Code Smoke Test 通用测试 Comm ...
- Android选择/拍照 剪裁 base64/16进制/byte上传图片+PHP接收图片
转载请注明出处:http://blog.csdn.net/iwanghang/article/details/65633129认为博文实用,请点赞,请评论,请关注.谢谢! ~ 老规矩,先上GIF动态图 ...
随机推荐
- 阻塞、非阻塞的概念和select函数的阻塞功能
其它文档: http://www.cnitblog.com/zouzheng/archive/2010/11/25/71711.html (1)阻塞block 所谓阻塞方式block,顾名思义 ...
- [Papers]NSE, $u$, Lorentz space [Bjorland-Vasseur, JMFM, 2011]
$$\bex \int_0^T\frac{\sen{\bbu}_{L^{q,\infty}}^p}{\ve+\ln \sex{e+\sen{\bbu}_{L^\infty}}}\rd s<\in ...
- hdu 1541 Stars(树状数组)
题意:求坐标0到x间的点的个数 思路:树状数组,主要是转化,根据题意的输入顺序,保证了等级的升序,可以直接求出和即当前等级的点的个数,然后在把这个点加入即可. 注意:树状数组下标从1开始(下标为0的话 ...
- bjfu1287字符串输出的大水题
不多说 /* * Author : ben */ #include <cstdio> #include <cstdlib> #include <cstring> # ...
- JDT入门
1.打开Java类型 要打开一个Java类或Java接口以进行编辑,可以执行以下操作之一: 在编辑器中所显示的源代码里选择所要编辑的Java类或Java接口的名字(或者简单地将插入光标定位到所要编辑的 ...
- 在刚接触TI-DM8127-ipnc框架时注意的问题
1. 修改内存分配不成功? 解决方法: 修改内存分配后需要重新编译mcfw.它影响3个核. 如果修改了cmem需要修改boostara. 2. 命令make clean后在make相机跑不起来? 解决 ...
- 【quick-cocos2d-x】Lua 语言基础
版权声明:本文为博主原创文章,转载请注明出处. 使用quick-x开发游戏有两年时间了,quick-x是cocos2d-Lua的一个豪华升级版的框架,使用Lua编程.相比于C++,lua的开发确实快速 ...
- 关于python中的__new__方法
在上篇中,简单的比较了下new方法和init方法,然后结合网上的东西看了一点,发现..看书有的时候说的并不全面. __new__方法是一个类方法,主要作用是来指导如何生成类的实例, 主要用于,当需要生 ...
- nagios监控远程主机服务可能出现的问题
1.使用插件NRPE监控命令不存在 在添加服务的时候,命令配置文件中需要传递一个参数,那么在监控服务配置文件中,需要添加一个!表示后面的为参数. 出现未定义的命令,查看被监控主机上的配置文件,添加监控 ...
- BITED数学建模七日谈之四:数学模型分类浅谈
本文进入到数学建模七日谈第四天:数学模型分类浅谈 大家常常问道,数学模型到底有哪些,分别该怎么学习,这样能让我们的学习有的放矢,而不至于没了方向.我想告诉大家,现实生活中的问题有哪些类,数学模型就有哪 ...