我有以下python多线程程序
#!/usr/bin/env python
from multiprocessing import Process
import time
child_started = False
def child_func():
global child_started
child_started = True
print "Child Started"
while True:
time.sleep(1)
print "X"
if __name__ == '__main__':
global child_started
child_thread = Process(target=child_func)
child_thread.start()
while child_started is False:
time.sleep(2)
print "Parent Starting Process"
# Do something
print "Parent Done"
child_thread.terminate()
print "Child Cancelled by Parent"
child_thread.join()
我期望子进程做一些工作,但最终父进程进入并终止它。然而,这没有发生。为什么?正如您在下面看到的,一旦子进程开始运行,Parent进程就会被冻结,从不做任何事情。为什么??如何解决。
$ ~/threads.py
~/threads.py:20: SyntaxWarning: name 'child_started' is assigned to before global declaration
Child Started
X
X
X
X
X
答案 0 :(得分:1)
正如@thepaul所说,你的child_started
变量是局部变量,并且在多处理通信之间不共享。
我建议你创建一个Queue
,一旦子进程开始,将一个元素放入队列并检查主进程中的queue.empty()
并开始工作。
#!/usr/bin/env python
from multiprocessing import Process
from multiprocessing import Queue
import time
def child_func(queue):
print "Child Started"
# put anything into queue after `child_func` get invoked, indicates
# your child process is working
queue.put("started...")
while True:
time.sleep(1)
print "X"
if __name__ == '__main__':
queue = Queue()
child_thread = Process(target=child_func,args=(queue,))
child_thread.start()
# stop sleeping until queue is not empty
while queue.empty():
time.sleep(2)
print "Parent Starting Process"
# Do something
print "Parent Done"
child_thread.terminate()
print "Child Cancelled by Parent"
child_thread.join()
答案 1 :(得分:0)
在child_started
函数中设置child_func
时,您正在设置局部变量,而不是全局模块级变量。此外,由于您使用的是多处理,因此这两个进程甚至不会共享全局变量。
您应该在参与的程序中传递带共享存储的内容,例如multiprocessing.Event
。
编辑:哎呀,我首先回答了这个问题,好像你使用的是线程而不是多处理。