python: can't terminate a thread hung in socket.recvfrom() call

Posted by Dihlofos on Stack Overflow See other posts from Stack Overflow or by Dihlofos
Published on 2010-04-06T14:40:41Z Indexed on 2010/04/06 14:43 UTC
Read the original article Hit count: 263

Filed under:
|
|

Hello, everyone

I cannot get a way to terminate a thread that is hung in a socket.recvfrom() call. For example, ctrl+c that should trigger KeyboardInterrupt exception can't be caught. Here is a script I've used for testing:

from socket import *
from threading import Thread
from sys import exit

class TestThread(Thread):
    def __init__(self,host="localhost",port=9999):
        self.sock = socket(AF_INET,SOCK_DGRAM)
        self.sock.bind((host,port))
        super(TestThread,self).__init__()

    def run(self):
        while True:
            try:
                recv_data,addr = self.sock.recvfrom(1024)
            except (KeyboardInterrupt, SystemExit):
                sys.exit()

if __name__ == "__main__":
    server_thread = TestThread()
    server_thread.start()
    while True: pass

The main thread (the one that executes infinite loop) exits. However the thread that I explicitly create, keeps hanging in recvfrom().

Please, help me resolve this.

© Stack Overflow or respective owner

Related posts about python

Related posts about threading