1

这个问题与A Django Related Question 有关

我正在使用 wsgiref.simple_server 运行一个 restlite WSGI 应用程序。我有这个设置,以便在 serve_forever() 方法被调用之前它初始化一些对象。最相关的是这些课程。

import Queue
import threading
import Deployer
import ParallelRunner
import sys
import subprocess

class DeployManager:
def __init__(self):
    self.inputQueue = Queue.Queue() 
    self.workerThread = DeployManagerWorkerThread(self.inputQueue)
    self.workerThread.start()   
def addDeployJob(self, appList):
    self.inputQueue.put(appList)  #make sure this handles the queue being full
def stopWorker(self):
    self.workerThread.running = False
def __del__(self):
    self.stopWorker()

class DeployManagerWorkerThread(threading.Thread):
def __init__(self, Queue):
    super(DeployManagerWorkerThread, self).__init__()
    self.queue = Queue
    self.running = True
    self.deployer = Deployer.Deployer()
    self.runner = ParallelRunner.ParallelRunner()

def run(self):
    while self.running:
        try:
            appList = self.queue.get(timeout = 10) #This blocks until something is in the queue
            sys.stdout.write('Got deployment job\n')
                            command = "ssh " + server.sshUsername + "@" + server.hostname + "" + " -i " + server.sshPrivateKeyPath + r" 'bash -s' < " + pathToScript 
                            self.process = subprocess.Popen(command,shell=True ,stdin=subprocess.PIPE, stdout=subprocess.PIPE)
            output = process.communicate()[0]
            sys.stdout.write(output + '\n')
        except Queue.Empty:
            pass
    sys.stdout.write('DeployManagerWorkerThread exiting\n')

restlite请求是这样设置的

@restlite.resource
def deployAll():
def POST(request, entity):
    GlobalDeployManager.addDeployJob(GlobalAppList) #TODO should runners be configurable at start up
    #print output                                               #or on a run by run basis
    return 'Job added'
return locals()

这会将一个条目放入队列中,然后 workerThread 将抓取并开始处理。然而,对 POpen 的调用总是挂起,我介入了它,它似乎挂在对 os.fork() 的调用中,这将“冻结”服务器。当线程到达 POpen 命令时,主线程位于它接受新请求的行。我相信服务器正在为此使用 epoll。如果队列中有多个作业,我可以在服务器正在运行的控制台上按 control-C,主线程将退出(不在等待请求的行),然后线程将能够运行按预期工作,然后关闭。有任何想法吗?

4

1 回答 1

0

我最终想通了……我需要在 run 方法中创建线程对象。我不小心忘记了init方法是从主线程调用的,然后新线程本身永远不会执行init

于 2012-10-24T19:04:02.180 回答