简体   繁体   English

在python中的进程之间共享/使用对象

[英]Sharing/using object between processes in python

I am trying to use an object (of class Event) between two processes. 我正在尝试在两个进程之间使用(事件类的)对象。 The main process creates the object (self.event) and passes it to the new process as args. 主进程创建对象(self.event)并将其作为args传递给新进程。 The new process will call the inject() method of the Event() in foo1() and again the main process will call restore when foo2() is called. 新进程将在foo1()中调用Event()的inject()方法,当foo2()被调用时,主进程将再次调用restore。

from multiprocessing import Process, Queue
class Event:
    def __init__(self):
        print('init')
        self.i = None
    def inject(self):
        print(self.i)
        self.i = 100
        print(self.i)
    def restore(self):
        print(self.i)


class Test:
    def __init__(self):
        self.event = Event()
    def foo1(self):
        p1 = Process(target=self.foo1_target, args=(self.event,))
        p1.start()
        p1.join()
    def foo1_target(self, event):
        event.inject()
    def foo2(self):
        self.event.restore()


t = Test()
t.foo1()
t.foo2()

When I run t.foo1(), it prints 当我运行t.foo1()时,它会打印

None 没有

100 100

When I run t.foo2(), it prints 当我运行t.foo2()时,它会打印

None 没有

My understanding is that t.foo2() should print 100. I am not able to understand why it prints None. 我的理解是t.foo2()应该打印100。我不明白为什么它打印None。 Also, how do I use Event object between main process and new process ? 另外,如何在主流程和新流程之间使用Event对象?

I was able to achieve that using Semaphores and Threads from threading. 我能够通过线程使用信号量和线程来实现。 :

from threading import Semaphore, Thread
class Event:
    def __init__(self):
        print('init')
        self.i = None
        self.sem = Semaphore(0)

    def inject(self):0
        print(self.i)
        self.i = 100
        print(self.i)
        self.sem.release()

    def restore(self):
        self.sem.acquire()
        print(self.i, "finished")



class Test:
    def __init__(self):
        self.event = Event() 
    def foo1(self):
        p1 = Thread(target=self.foo1_target, args=())
        p1.start()
        p1.join()
    def foo1_target(self):
        self.event.inject()

    def foo2(self):
        self.event.restore()



if __name__ == '__main__':
    t = Test()
    t.foo1()
    t.foo2()

output 输出

init
None
100
100 finished

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM