2013-02-09 101 views
0

我正在使用python编写的服务器上工作。当客户端发送一个cmd时,服务器将调用一个未知运行时间的函数。所以为了避免阻塞,我使用了线程。但是当看着子进程看起来他们没有终止,导致大量的内存使用。 编辑:这里是目录树:http://pastebin.com/WZDxLquC以正确的方式使用线程

如下回答我的计算器我实现了一个自定义的Thread类发现:

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类不会解决问题,它仍然不会终止已终止的线程!

编辑:添加了手柄()和响应()方法:

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 ! 
+1

'serve_forever()'有七个级别的嵌套循环和ifs。我不知道它实际上应该做什么?它中的所有代码是否与您所看到的问题真正相关?您所运行的线程的代码也不包括在内。一旦'handle()'和'respond()'完成,线程应该会自动停止。 – millimoose 2013-02-09 12:17:51

+1

另外,在我看来,你似乎为每个客户端连接启动了多个线程,这听起来像是一场灾难 - 如果他们全部从客户端连接读取/写入到同一时间怎么办?如果(self.workers == 0和len(self.currentThreads)> 0)' – millimoose 2013-02-09 12:20:51

+0

@ millimoose:1-在运行测试时,handle()和respond()真的完成了,但是线程并没有自动停止! 2-不是每个客户端连接都收到每条消息的线程 – rednaks 2013-02-09 12:40:13

回答

0

似乎self.queue.get()是导致所有的问题...