Python3共享状态对象

时间:2019-01-26 14:49:09

标签: python-3.x python-multiprocessing shared-state

我有这个代码,理论上应该可以正常工作。但是它陷入僵局,我找不到原因。我正在尝试共享一个类的对象,并从流程中同步对其成员的访问。

因此,我认为将同步对象包含在类中是可行的,但是没有用。

我该如何实现?

这是我当前的代码:

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

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

class info(object):  
    def __init__(self):  
        self.nl = []
        self.lock = Lock()  
        self.waitC = Condition(self.lock)  
        self.waitP = Condition(self.lock)  

        # self.lock.acquire()
        # self.waitP.notify()
        # self.lock.release()


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

    def stampa(self):  
        self.lock.acquire()
        # print(24)
        self.waitC.wait()
        print (self.nl)  

        self.waitP.notify()
        self.lock.release()

    def appendi(self, x):  
        self.lock.acquire()
        self.waitP.wait()
        print(36)
        if x is list:
            for new_value in x:
                self.nl.append(new_value)
        else:
             self.nl.append(x) 

        self.waitC.notify()

        self.lock.release()


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


class numManager(BaseManager):  
    pass  

numManager.register('info', info, exposed = ['getLen', 'appendi', 'svuota', 'stampa'])
# numManager.register('lock', lock, AcquirerProxy)
# numManager.register('waitP', waitP, AcquirerProxy)
# numManager.register('waitC', waitC, AcquirerProxy)


def consume(listaNumeri):  
    print(53) 

    listaNumeri.stampa()
    listaNumeri.svuota()  
    # print(55) 
    # time.sleep(1.1)
    # listaNumeri.stampa()
    # listaNumeri.svuota()  

def produce(listaNumeri): 
    times = 0
    while times<4: 
        insert = []
        for i in range(10):
            insert.append(i)

        print(63)
        listaNumeri.appendi(insert)
        time.sleep(1)

        insert = []
        for i in range(7):  
            insert.append(i*(-1))  
        listaNumeri.appendi(insert)

        times = times+1

def main():  
    mymanager = numManager()  
    mymanager.start()  
    info = mymanager.info()  
    producer = Process(target = produce, args =(info,))  
    producer.start()  

    time.sleep(2)

    consumer = Process(target = consume, args =(info,))  
    consumer.start() 


    consumer.join()
    print("consumer finished")
    producer.join()


if __name__ == '__main__':
    freeze_support()
    main() 

我故意留下了一些注释代码,以便您可以了解我的思想模式并指出任何错误。

0 个答案:

没有答案