首页 > 解决方案 > 设置多线程 Pyro 项目

问题描述

我必须构建一个简单的分布式环结构 p2p 系统,其中生产者和消费者相互交互以进行交易。我们需要使用线程或套接字来构建它。我一直在使用 Pyro,但我不知道如何处理生产者或消费者线程。理想情况下,消费者会产生一个线程来向其两个邻居发送请求。邻居可以是消费者或生产者,并将请求转发给他们的邻居。如果找到生产者,则在 prod 和 cons 之间建立直接连接并进行交易之前,该请求应追溯至源(消费者)。

需要为每条新消息生成线程或管理线程池。到目前为止,我有一个 Pyro 类,它看起来像:

import threading

import Pyro4

class Peer(object):

     def __init__():
         #sets up quantity, lock, id, neighbourlist
         #neighbour list has max 2 entries

     def lookup():
         # creates a msg object to be sent to forward()

     def forward():
         #sends msg to neighbors by creating proxies and calling 
         #the receive method on them

     def receive():
         #called when a msg is received. acquires lock and accesses the 
         #quantity. releases lock if not a producer or quantity is low    

class Message(object):
      def __init__(params):
          #sets up a message object with the given params like  
          #msgid, consumerid, quan, producerid, forwarder_id(so that the message is not sent backwards)

我试图使 Peer 类成为 threading.Thread 类的子类,但是当我使用 Pyro 代理调用线程的 start() 方法时,它给了我一个错误:

AttributeError: 远程对象 'PYRO:obj_32f7c4e3f79146ac94a3389303e45361@localhost:35275' 没有暴露的属性或方法 'start'

远程对象不能访问超类方法吗?我该如何解决这个问题?

标签: pythonmultithreadingrmidistributed-systempyro

解决方案


没错,按照设计,Pyro 只允许您调用显式公开的远程方法。这意味着超类中的方法不会暴露。

无论如何,有几种方法可以远程访问它们(请参阅https://pyro4.readthedocs.io/en/stable/servercode.html#exposing-classes-and-methods-without-sharing-existing-source-code),但事实并非如此在这种情况下的解决方案。您可能不想远程控制服务器处理并发(在本例中为线程)的方式。

为什么不利用 Pyro4 使用的默认服务器类型已经是多线程服务器这一事实呢?您可以控制 Pyro 处理对象方式的某些方面(例如,如果需要,让它为每个调用创建一个新实例) https://pyro4.readthedocs.io/en/stable/servercode。 html#controlling-instance-modes-and-instance-creation

最后,Pyro4 附带了一些已经实现了聊天框和消息系统的示例,因此您可能想看看那些(至少是聊天框和消息总线),也许它们可以向您展示您想要做的替代解决方案.


推荐阅读