使用管理者在python共享对象(类的实例)(Sharing object (class insta

2019-06-27 01:23发布

我需要共享一个对象及其在蟒蛇几道工序之间的方法。 我试图用管理器(模块多),但它崩溃。 这里是生产者 - 消费者的傻示例,其中在两个过程之间的共享对象仅仅是一个具有四个方法号码列表。

from multiprocessing import Process, Condition, Lock  
from multiprocessing.managers import BaseManager  
import time, os  

lock = Lock()  
waitC = Condition(lock)  
waitP = Condition(lock)  

class numeri(object):  
    def __init__(self):  
        self.nl = []  

    def getLen(self):  
        return len(self.nl)  

    def stampa(self):  
        print self.nl  

    def appendi(self, x):  
        self.nl.append(x)  

    def svuota(self):  
        for i in range(len(self.nl)):  
            del self.nl[0]  

class numManager(BaseManager):  
    pass  

numManager.register('numeri', numeri, exposed = ['getLen', 'appendi', 'svuota', 'stampa'])  

def consume(waitC, waitP, listaNumeri):  
    lock.acquire()  
    if (listaNumeri.getLen() == 0):  
        waitC.wait()  
    listaNumeri.stampa()  
    listaNumeri.svuota()  
    waitP.notify()  
    lock.release()  

def produce(waitC, waitP, listaNumeri):  
    lock.acquire()  
    if (listaNumeri.getLen() > 0):  
        waitP.wait()  
    for i in range(10):  
        listaNumeri.appendi(i)  
    waitC.notify()  
    lock.release()  


def main():  
    mymanager = numManager()  
    mymanager.start()  
    listaNumeri = mymanager.numeri()  
    producer = Process(target = produce, args =(waitC, waitP, listaNumeri,))  
    producer.start()  
    time.sleep(2)  
    consumer = Process(target = consume, args =(waitC, waitP, listaNumeri,))  
    consumer.start()  

main() 

反正它总是崩溃那样,告诉我这一点:

Process Process-3:
Traceback (most recent call last):
  File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
    self.run()
  File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
    self._target(*self._args, **self._kwargs)
  File "./trySemProc.py", line 61, in consume
    if (listaNumeri.getLen() == 0):
  File "<string>", line 2, in getLen
  File "/usr/lib/python2.7/multiprocessing/managers.py", line 755, in _callmethod
    self._connect()
  File "/usr/lib/python2.7/multiprocessing/managers.py", line 742, in _connect
    conn = self._Client(self._token.address, authkey=self._authkey)
  File "/usr/lib/python2.7/multiprocessing/connection.py", line 169, in Client
    c = SocketClient(address)
  File "/usr/lib/python2.7/multiprocessing/connection.py", line 293, in SocketClient
    s.connect(address)
  File "/usr/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
error: [Errno 2] No such file or directory

那么,有什么事? 我应该如何使用这些管理者分享对象及其方法?

Answer 1:

你必须加入你的流程,以防止主进程退出之前子进程继续执行。 所以加连结到你的代码:

 consumer.join()
 producer.join()

以后你叫start()的过程的方法。



文章来源: Sharing object (class instance) in python using Managers