Shutting down a cross-platform multithreaded app

James Harris james.harris.1 at
Fri Sep 18 21:09:19 CEST 2015

"Paul Rubin" < at nospam.invalid> wrote in message 
news:87zj0jd1ta.fsf at
> "James Harris" <james.harris.1 at> writes:

>> I have a multithreaded app that I want to be able to shut down easily
>> such as by hitting control-c or sending it a signal.
> Set the daemon flag on the worker threads, so when the main thread
> exits, the workers also exit.

Interesting idea, and I did not know that a *thread* could be a daemon. 
Unfortunately, I think what you suggest would kill the threads stone 
dead and not allow them to close connections.

That's a particular problem with TCP connections and would require the 
OS to keep TCP state around for a while. I would rather close the TCP 
connections or, rather, encourage the other end to close the connection 
so that the worker threads could then close the sockets in a way that 
would not hold on to resources.

For anyone who is interested see the TCP state diagram such as the one 

The key transition is the way the server exits the ESTABLISHED state. If 
the server closes its end of the connection first the transition goes 
via the line labelled appl:close, send: FIN. In that case the socket 
will end up in the TIME_WAIT state wherein it can wait 2MSL or 2 maximum 
segment lifetimes before becoming free.

According to

MSL is arbitrarily defined to be two minutes. That means a TCP endpoint 
could sit in TIME_WAIT for a horribly long four minutes...!

So, I would rather get the other end to send the first FIN, if possible. 
On the TCP state diagram that is the exit from ESTABLISHED labelled 
recv:FIN, send ACK. My end can then shutdown the socket, which would 
send a FIN, and wait for a final ACK.

Bottom line: I need to do a controlled cleanup.


More information about the Python-list mailing list