main0
不会挂起但main1
挂起。为什么???我认为将这个东西包装成一个类应该是无害的......
子进程应该只是将收到的消息发送回主进程。
Python3代码:
from multiprocessing import Process, Pipe
def child(conn):
print("child started")
while True:
msg = conn.recv()
if msg == "quit":
break
print("child recv:"+msg)
print("child sending:" + msg)
conn.send(msg)
conn.close()
print("child ended")
def main0():
parent_conn, child_conn = Pipe()
p = Process(target=child, args=(child_conn,))
p.start()
parent_conn.send("ping")
print(parent_conn.recv())
parent_conn.send("quit")
print("#parent ended#")
p.join()
class Parent(object):
def __init__(self):
self.parent_conn = None
self.child_conn = None
self.p = None
def start(self):
self.parent_conn, self.child_conn = Pipe()
self.p = Process(target=child, args=(self.child_conn,))
self.p.start() # <--- i initially missed this line
print("started")
def send(self, msg):
print("try to send: " + msg)
self.parent_conn.send(msg)
return self.parent_conn.recv()
def close(self):
self.parent_conn.send("quit")
self.p.join()
def main1():
a = Parent()
a.start()
print(a.send("ping"))
print(a.send("quit"))
a.close()
if __name__ == '__main__':
main0() # doesn't hang
main1() # hangs.
输出:
~~~ main 0 ~~~
child started
child recv:ping
child sending:ping
ping
#parent ended#
child ended
~~~ main 1 ~~~
started <Process(Process-1, started)>
try to send: ping
waiting to recv
child started
child recv:ping
child sending:ping
ping
try to send: quit
waiting to recv
child ended
*still hangs ... after adding self.p.start()*
答案 0 :(得分:0)
我在start方法中错过了self.p.start()
行。
向儿童发送quit
消息也不会返回任何消息。
正确的main1()
应为:
def main1():
a = Parent()
a.start()
print(a.send("ping"))
a.close()
然后这是固定的。