How to exit a multithreaded program?

前端 未结 2 635
闹比i
闹比i 2020-12-10 07:16

I was just messing around with threading in python, wrote this basic IM thingy [code at bottom]

I noticed that when I kill the program with C-c it doesn\'t exit, it

2条回答
  •  难免孤独
    2020-12-10 07:51

    Look at the Python library source for SocketServer.py, in particular the implementation of server_forever() to see how a server implements a quit. It uses select() to poll the server socket for new connections and tests a quit flag. Here's a hack on your source to use SocketServer, and I added a quit flag to Shout(). It will run the Shout and Listen threads for 5 seconds and then stop them.

    import socket
    import SocketServer
    import threading
    import time
    
    class Handler(SocketServer.StreamRequestHandler):
        def handle(self):
            print str(self.client_address) + ": " + self.request.recv(250)
            self.request.send("got it\n")
    
    class Listen(threading.Thread):
        def run(self):
            self.server = SocketServer.TCPServer(('',2727),Handler)
            self.server.serve_forever()
        def stop(self):
            self.server.shutdown()
    
    class Shout(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
            self.quit = False
        def run(self):
            while not self.quit:
                conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                conn.connect(('localhost', 2727))
                conn.send('sending\n')
                print conn.recv(100)
                conn.close()
        def stop(self):
            self.quit = True
    
    listen = Listen()
    listen.start()
    shout = Shout()
    shout.start()
    
    time.sleep(5)
    
    shout.stop()
    listen.stop()
    

提交回复
热议问题