0

I am trying to run a thread within a thread. When I execute monitor.startMonitoring(), it gets stuck in that function, specifically on threading.Thread(target=self._startMonitoring(), daemon=True).start().

What can I do so I can go to the last line (print function call) of the code?

host = '127.0.0.1'
port = 9000

def _receiveHealthMsg(clientsock, clientaddr):
    try:
        while True:
            print(f'{clientaddr} : {clientsock.recv(1024).decode("utf-8")}: '
                  f'{datetime.datetime.now().isoformat()}')
    except ConnectionResetError:
        print("Connection has been severed")


class Monitor:
    def __init__(self, host, port):
        self._sock = socket.socket()
        self._sock.bind((host, port))
        self._sock.listen(5)
        self._threads = []
        self._clients = []

    def startMonitoring(self):
        threading.Thread(target=self._startMonitoring(), daemon=True).start()

    def _startMonitoring(self):
        while True:
            c, addr = self._sock.accept()
            thread = threading.Thread(target=_receiveHealthMsg, args=(c, addr))
            thread.start()
            self._threads.append(thread)
            self._clients.append((c, addr))

monitor = Monitor(host, port)
monitor.startMonitoring()

print('do some stuff here while threads are running')
martineau
  • 119,623
  • 25
  • 170
  • 301
AznBoyStride
  • 305
  • 2
  • 12

1 Answers1

0

You called _start_monitoring, you didn't pass it as a function to run. Change the line to:

threading.Thread(target=self._startMonitoring, daemon=True).start()
                                           # ^ parentheses removed
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271