gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:16:05 24 4
gpt4 key购买 nike

我已经在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”。为什么队列在守护进程中不起作用?

最佳答案

我怀疑您看到这种奇怪的行为是因为您在守护进程之前运行了一堆代码,这在内部执行 os.fork() 。这会让你处于一种奇怪的状态,其中一些代码在一个进程中启动,但随后你 fork (意味着你得到了一个新进程)并开始尝试使用你在 fork 之前创建的那些对象,这将无法正常工作。例如,所有正在运行的线程都将被终止。您需要将所有代码移至with daemon_context block 内才能开始工作。

不过,我会对此小心谨慎。使用 while True 循环,您可以快速地将相当多的数据写入磁盘。

关于python - 在守护进程中运行线程+队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24983314/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com