Hi guys,
I write a python program to implement functions in a ConnectPort X4 gateway as following:
(1) A TCP server for listening new clients connect request
(2) Once a new request detected, TCP server accepts it and start a new thread for this client socket connection. TCP clients send requests via independent sockets and the client handling threads process the requests and put them into ZigBee server (see (3)) request queue.
(3) a ZigBee server scan request queue (data put by TCP client threads) and forward the request to specified nodes in ZigBee network.
The reason I use multithread is to support multi-clients connected simultaneously. Because the client connection may be created and disconnected frequently (just like http connection), the TCP server will create a lot of threads after the system run for a couple of minutes. Then the error is comming:
Exception in thread Thread-1:
Traceback (most recent call last):
File “./threading.py”, line 442, in __bootstrap
File “D:\Users\joeytian\workspace\lms_cpx4_server runk\lms_cpx4_server\src ulip_tcp_server.py”, line 61, in run
File “D:\Users\joeytian\workspace\lms_cpx4_server runk\lms_cpx4_server\src ulip_tcp_server.py”, line 88, in listen
File “./threading.py”, line 416, in start
error: can’t start new thread
I think this may be caused by the improper thead termination when each TCP client connection closed. I write the code of the TCP client thread like this(just the run() shown here, self.close is set by TCP server thread when a disconnect empty byte received from listening socket):
def run(self):
# only check data rx/tx
self.close = False
r_list = [self.c_skt]
w_list = r_list
while (not self.close):
try:
s_read, s_write = select(r_list, w_list, [])[:2]
# scan readable list
# if(self.c_skt in s_read):
if(len(s_read) > 0):
self.__rx_handler__()
#if(self.c_skt in s_write):
if(len(s_write) > 0):
self.__tx_handler__()
#request process
self.process_request()
except:
print "Thread quit because of exception!"
raise
Another problem may be some resources are not released when this thread exits because they may be used by other thread (such as Zigbee server thread uses a reference of the TCP client thread variables).
So my question is simple but not easy to give a short answer:
How to terminate or quit from a thread?