多处理池错误“条件对象只能通过继承在进程之间共享”

时间:2019-12-01 14:51:05

标签: python python-3.x multiprocessing pool

我有以下代码,该代码使用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解决此问题的建议吗?

0 个答案:

没有答案