以正确的方式使用线程

时间:2013-02-09 12:15:01

标签: python multithreading

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

我在stackoverflow上找到了以下答案,我实现了一个自定义的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类无法解决问题,但仍然无法停止已终止的线程!

编辑:添加了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 !

1 个答案:

答案 0 :(得分:0)

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