user3057275
user3057275

Reputation:

How can i stop a socket thread in Python?

In Python 3.3.3, i create a thread to listen some connection to the socket.It likes this:

import threading
import socket
import time

Host = ''
Port = 50000

flag = False

class ServerThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    def run(self):
        try:
            self._sock.bind((Host, Port))
            self._sock.listen(5)
            while True:
                conn, addr = self._sock.accept()
                print('Connected by', addr)
        except socket.error as msg:
            print(msg)
        except Exception as e:
            print(str(e))
        finally:
            self._sock.close()
    def exit(self):
        self._sock.close()

def TargetFunc(vlock):
    vlock.acquire()
    flag = True
    vlock.release()

def main():
    sthread = ServerThread()
    sthread.start()
    vlock = threading.Lock()
    time.sleep(10)
    vthread = threading.Thread(target = TargetFunc, args = (vlock, ))
    vthread.start()
    while True:
        vlock.acquire()
        if flag:
            sthread.exit()
            vlock.release()
            break
        vlock.release()
    sthread.join()
    vthread.join()

if __name__ == '__main__':
    main()

There are two threads, one is listening socket, the other is to set a flag. When the flag is True, close the socket, then raise a socket error and catch it, so the listening socket terminates.But why it does not work this.

Thanks!

Upvotes: 1

Views: 514

Answers (1)

Sorin
Sorin

Reputation: 11968

self._sock.accept() is blocking. So it will wait until somebody connects. You should use a nonblocking variant (or blocking but with a time-out). So that you can check the exit conditions.

Alternatively you could force an exception in the ServerThread.

Upvotes: 3

Related Questions