delphi - terminate all the threads (TThread) on closing application

后端 未结 3 487
无人及你
无人及你 2020-12-29 16:28

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

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-29 17:03

    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

提交回复
热议问题