Python : how to stop a thread that's waiting for a .recv()

后端 未结 2 1209
生来不讨喜
生来不讨喜 2021-01-20 03:22

I have this thread running :

def run(self):
    while 1:
        msg = self.connection.recv(1024).decode()

I wish I could end this thread

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-20 03:51

    Two solutions:

    1) Don't stop the thread, just allow it to die when the process exits with sys.exit()

    2) Start the thread with a "die now" flag. The Event class is specifically designed to signal one thread from another.

    The following example starts a thread, which connects to a server. Any data is handled, and if the parent signals the thread to exit, it will. As an additional safety feature we have an alarm signal to kill everything, just it case something gets out of hand.

    source

    import signal, socket, threading
    
    class MyThread(threading.Thread):
        def __init__(self, conn, event):
            super(MyThread,self).__init__()
            self.conn = conn
            self.event = event
    
        def handle_data(self):
            "process data if any"
            try:
                data = self.conn.recv(4096)
                if data:
                    print 'data:',data,len(data)
            except socket.timeout:
                print '(timeout)'
    
        def run(self):
            self.conn.settimeout(1.0)
            # exit on signal from caller
            while not self.event.is_set():
                # handle any data; continue loop after 1 second
                self.handle_data()
            print 'got event; returning to caller'
    
    
    sock = socket.create_connection( ('example.com', 80) )
    event = threading.Event()
    
    # connect to server and start connection handler
    th = MyThread(conn=sock, event=event)
    
    # watchdog: kill everything in 3 seconds
    signal.alarm(3)
    
    # after 2 seconds, tell data thread to exit 
    threading.Timer(2.0, event.set).start()
    
    # start data thread and wait for it
    th.start()
    th.join()
    

    output

    (timeout)
    (timeout)
    got event; returning to caller
    

提交回复
热议问题