我正在研究用python编写的服务器。当客户端发送 cmd 时,服务器将调用一个运行时间未知的函数。所以为了避免阻塞,我使用了线程。但是当查看子进程时,它们似乎没有终止,导致大量内存使用。编辑:这是目录树:http: //pastebin.com/WZDxLquC
按照我在stackoverflow上找到的答案,我实现了一个自定义线程类:
sThreads.py:
import threading
class Thread(threading.Thread):
def __init__(self, aFun, args = ()):
super(Thread, self).__init__(None, aFun, None, args)
self.stopped = threading.Event()
def stop(self):
self.stopped.set()
def isStopped(self):
return self.stopped.isSet()
然后是服务器的循环:
mainServer.py 中的一些地方:
def serve_forever(self, aCustomClass, aSize = 1024):
while True:
self.conn, self.addr = self.sock.accept()
msg = self.recvMSG(4096)
if(msg):
self.handShake(msg)
print 'Accepted !'
while True:
msg = self.recvMSG(aSize)
if(msg):
t = sThreads.Thread(self.handle, (aCustomClass,))
t.start()
self.currentThreads.append(t)
if(self.workers > 0):
tt = sThreads.Thread(self.respond)
tt.start()
if(self.workers == 0 and len(self.currentThreads) > 0):
for th in self.currentThreads:
th.stop()
使用自定义 Thread 类不会解决问题,它仍然不会停止终止的线程!
编辑:添加了 handle() 和 respond() 方法:
def handle(self, aClass):
self.workers += 1
self.queue.put(aClass._onRecieve(self.decodeStream()))
def respond(self):
while self.workers > 0:
msgToSend, wantToSend = self.queue.get()
self.workers -= 1
if(wantToSend):
print 'I want to send :', msgToSend
continue #Send is not yet implemented !