我有以下代码,该代码使用Pipe
在Python 3.7(MacOSX)中在发送方和接收方之间进行通信
import multiprocessing as mp
import time
class Sender:
def __init__(self, conn):
self.event = mp.Event()
self.conn = conn
def sender(self):
while not self.event.is_set():
time.sleep(1)
self.conn.send(True)
def close(self):
self.event.set()
self.conn.close()
print("Closing Sender...")
class Receiver:
def __init__(self, conn):
self.event = mp.Event()
self.conn = conn
def receiver(self):
while not self.event.is_set():
print("Starting...")
msg = self.conn.recv()
if msg:
print("Received the message: {}".format(msg))
def close(self):
self.event.set()
self.conn.close()
print("Closing Receiver...")
if __name__ == "__main__":
# creating a pipe
parent_conn, child_conn = mp.Pipe()
sender = Sender(parent_conn)
receiver = Receiver(child_conn)
# creating new processes
with mp.Pool(4) as pool:
pool.apply_async(sender.sender).get()
pool.apply_async(receiver.receiver).get()
time.sleep(10)
sender.close()
receiver.close()
当我尝试运行此命令时,出现以下错误:“ RuntimeError:条件对象仅应通过继承在进程之间共享”。我尝试删除.get()
中的apply_async
,但是它只是挂起了(大概在recv()
的{{1}}中)。我使用普通的receiver()
进行了尝试,效果很好。那么Process
有什么问题?是因为Pool
对象?还有关于如何使用Connection
解决此问题的建议吗?