delphi - 在关闭应用程序时终止所有线程(TThread) [英] delphi - terminate all the threads (TThread) on closing application

查看:1234
本文介绍了delphi - 在关闭应用程序时终止所有线程(TThread)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序是一个tcp / ip服务器,主线程只创建一次&一直听着当新客户端连接时,主线程创建新线程 TClientThread 类型。然而,没有列出运行的客户端线程,因为这会使我的应用程序有点复杂...有什么办法在所有线程上执行terminate方法,即使线程很忙(在我的情况下忙意味着它正在等待数据,超时时间大约为30秒...所以我不得不杀死它,而不用等待。)
简单的关闭应用程序似乎没有在线程上运行terminate方法,最终导致FastMM报告的内存泄漏...

解决方案关闭时的内存泄漏无关紧要 - 在将控制权返回到操作系统之前,要释放内存的麻烦是浪费时间,不必要地减慢应用程序退出时间。您真正需要做的是确保所有数据已被保存,并且所有进程间处理(如信号量和互斥体)正确释放,并退出。



为了通知客户端,你最好的做法就是这样一种策略:




  • 将所有客户端处理线程添加到某个列表锁定创建,销毁和迭代)

  • 使客户端线程在终止时将其从列表中删除,并从列表中删除最后一个项目设置事件(手动重置事件,例如<$如果服务器正在关闭,则在SyncObjs中的c $ c> TEvent

  • 引入轮询(例如 select 或等效的超时)或其他类型的中断(例如SO_RCVTIMEO / SO_SNDTIMEO),否则将是长期运行的阻塞例程,监视终止的属性

  • 在关闭时,锁定列表,迭代,调用终止,然后等f或要发信号的事件;当然,在列表中添加项目的监听套接字应该被关闭,并且在迭代列表之前已经被关闭了


My application is a tcp/ip server, with main thread created only once & listening all the time. When new client connects, the main thread creates the new thread of TClientThread type. There is however no list of running Client threads, as that would make my app a bit complicated... is there any way to execute "terminate" method on all the threads, even if the thread is busy (in my case "busy" means it's waiting for the data, where the timeout set is about 30 sec ... so I have to kill it anyway, without waiting.)? The simple closing application seems not to run "terminate" method on the threads, which ends up with memory leaks reported by FastMM...

解决方案

Memory leaks on shutdown are nothing to worry about - going to the trouble of freeing memory before returning control to the operating system is a waste of time and needlessly slows down application exit. All you really need to do is ensure that all data has been saved, and all interprocess handles (such as semaphores and mutexes) correctly released, and exit away.

For notifying clients, the best you can do would be a strategy somewhat like this:

  • Add all client-handling threads to some list somewhere (with suitable locking on creation, destruction and iteration)
  • Make client threads remove themselves from the list upon termination, and have the last item removed from the list set an event (manual reset event, e.g. TEvent in SyncObjs) if the server is shutting down
  • Introduce polling (e.g. select or equivalent with a timeout) or other kind of interruption (e.g. SO_RCVTIMEO / SO_SNDTIMEO) in what would otherwise be long-running blocking routines, monitoring the Terminated property
  • On shutdown, lock the list and iterate through it, calling Terminate, and then wait for the event to be signaled; of course, the listening socket which adds items to the list should be closed and known to be closed before iterating through the list

这篇关于delphi - 在关闭应用程序时终止所有线程(TThread)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆