我一直在试验多重处理,并遇到了一个带有守护进程的思维块。
我有一个守护进程和一个非守护进程,守护进程无限期地每1秒发出一次输出,而非守护进程在开始时立即打印输出,休眠3秒,然后再次打印并返回。
问题是,守护进程的预期输出根本没有显示出来。
回顾过去关于守护进程的问题,常见的问题似乎要么是在守护进程之前结束的其他进程,要么是需要刷新以显示输出的标准输出。这两种方法(我认为)都已经解决了,但是我仍然只看到非守护进程的打印输出。
代码:
from multiprocessing import Process, current_process
import sys
import time
def worker():
"""
Announce that the process has started, sleep 3 seconds
then announce that the process is ending.
"""
name = current_process().name
print name, 'starting...'
sys.stdout.flush()
time.sleep(3)
print name, 'ending...'
sys.stdout.flush()
return
def daemon():
"""
Announce that the process has started, beep, then beep
once every second
"""
name = current_process().name
print name, 'starting...'
print 'beep...'
sys.stdout.flush()
while True:
time.sleep(1)
print 'beep...'
sys.stdout.flush()
if __name__=='__main__':
d = Process(target=daemon)
d.daemon = True
d.start()
p = Process(target=worker)
p.daemon = False
p.start()预期输出:
Process-1 starting... # Order here may vary
beep...
Process-2 starting...
beep...
beep...
Process-2 ending... #There may or may not be another beep here实际产生的内容:
Process-2 starting...
Process-2 ending...任何关于为什么会发生这种情况的建议都会得到真正的感谢。
发布于 2014-12-31 11:18:22
通过打开日志,您可以更清楚地了解事件的顺序
import multiprocessing as mp
logger = mp.log_to_stderr(logging.INFO)在其他导入语句之后。然后,您的程序将产生如下内容:
[INFO/Process-1] child process calling self.run()
[INFO/MainProcess] process shutting down
Process-1 starting...
beep...
[INFO/Process-2] child process calling self.run()
[INFO/MainProcess] calling terminate() for daemon Process-1
Process-2 starting...
[INFO/MainProcess] calling join() for process Process-2
Process-2 ending...
[INFO/Process-2] process shutting down
[INFO/Process-2] process exiting with exitcode 0
[INFO/MainProcess] calling join() for process Process-1因此,主进程首先开始关闭,然后终止进程-1,守护进程进程。这就是为什么在进程-2继续的时候,你看不到更多的嘟嘟声。
https://stackoverflow.com/questions/27720281
复制相似问题