How to stop a thread?

sismex01 at hebmex.com sismex01 at hebmex.com
Thu Oct 10 16:22:48 EDT 2002


> From: marvelan at hotmail.com [mailto:marvelan at hotmail.com]
> 
> How can I stop a thread that is waiting to handle a TCP
> socket? 
> 
> As there is no kill thread function in Python my first idea 
> was to do a handle_request until I set a global magical_flag. 
> 
> But then I realised that this works only when I have a steady
> flow of connections comming in. Otherwise it will just hang
> (as it should) in handle_request and thus the thread would
> never stop.

AH-HAH!!

Someone else with my same questions... :-)

> 
> So, how can I stop the thread in the example below? I would
> like to stop it when user presses the "stop" button in some
> way.
> 
> 
> class Foo(Thread):
>  
>     def run(self):
>         self.server = SocketServer.ThreadingTCPServer(addr, h)
> 
>         while not magical_flag:
>             self.server.handle_request()
>

I did something almost-but-not-quite-completely-unlike your
approach.  Mine's an HTTP server class with an inner loop
which listens for connections on the server socket,
but same as you, I didn't know how to wait for a
connection-yet-still-have-control.

It seems like select() is our friend here.

My loop loops a little like this:

   def accept_request(self):
      # Wait up to self._timeout seconds for incoming request.
      l = select.select([self._socket], [], [], self._timeout)
      # IF there's a request, accept connection. Else, exit.
      if l:
         csock, caddr = self._socket.accept()
         ident = self.request_ident(caddr)
         self.log("Got request from ", Client=caddr, ID=ident)
         self.dispatch_request(csock, caddr, ident)

This little function __THEORETICALLY__ first checks if there's
incoming data on the socket for up to self._timeout seconds,
if there is, then it accepts the connection and processes
the request; else, it exits.

This helps a little, because I can tell the server between
calls to this function to exit if so-and-so conditions. Also,
having a non-zero timeout helps out all other threads.

Salutations all :-)

-gustavo





More information about the Python-list mailing list