在守护进程中运行线程+队列

时间:2014-07-27 17:00:57

标签: python multithreading python-multithreading python-daemon

我已经在Python文件 myfile.py 中成功实现了线程+队列。现在我希望这个文件作为守护进程运行,因为当所有线程都完成了他们的任务时,我想重新填充队列并让线程处理新任务。我在这里尝试一些代码,但程序没有正确响应:

# myfile.py

threadList = list()
i = 0
while i < 10:
    i += 1
    threadName = "T" + str(i)
    threadList.append(threadName)

#create queue
myQueue = Queue.Queue();

# create thread objects
threads = list()
for threadName in threadList:
    thread = WorkerThread(threadName, myQueue)
    thread.start()
    threads.append(thread)

def hello():    
    while True:
        logger.debug("true")
        if myQueue.empty():
            logger.debug("empty")
        else:
            logger.debug("not empty")

def run():
    daemon_context = daemon.DaemonContext(files_preserve=[handler.stream],
                                          stdout = open("./stdout.log","wb"),
                                          stderr = open("./stderr.log","wb"))
    with daemon_context:
        hello()

if __name__ == "__main__":
    run()

执行脚本时,它会打印“true”并停在那里。它不会记录“空”或“非空”。终端和stderr.log中没有显示错误。但是,如果我删除myQueue.empty()的条件检查,守护程序将继续打印“true”。为什么队列在守护进程中不起作用?

1 个答案:

答案 0 :(得分:1)

我怀疑你是否看到了这种奇怪的行为,因为你在守护之前运行了一堆代码,这在内部正在进行os.fork()。这让你处于一个奇怪的状态,你的一些代码在一个进程中启动,然后你分叉(意味着你得到一个新的进程)并开始尝试使用你在fork之前创建的那些对象,这些对象赢了& #39;工作正常。例如,所有正在运行的线程都将被杀死。您需要在with daemon_context块内移动所有代码才能开始工作。

但是,我会小心这一点。您正在使用while True循环快速写入磁盘。

相关问题