卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章64334本站已运行4115

Python 中进程之间不共享实例变量

python 中进程之间不共享实例变量

问题内容

我在多重处理方面遇到了大问题。在这种情况下我有一个

1.主进程中的主类

2.另一个进程中的foo类

我必须使用主进程更改 process2 内部的一些变量。 我怎样才能做到这一点/???

class Main:
     def __init__(self):
          self.Foo_Instance = Foo()
          multiprocessing.Process(target=self.Foo_Instance.do_something).start()

     def Change_Foo(self):
          Foo_Instance.ImportantVar = True
    
class Foo:
     def __init__(self):
          self.ImportantVar = False

     def do_something(self):
          pass

Main_Instance = Main()
Main_Instance.Change_Foo()


正确答案


每个进程通常都有自己的内存,任何其他进程都无法访问该内存。如果您希望一个进程能够修改另一个进程正在使用的变量,那么最简单的解决方案是在共享内存中创建该变量。在下面的演示中,我们使用 multiprocessing.value实例。为了证明 main.change_foo 可以修改 fooimportantvar 属性,我们必须在 main.change_foo 修改它之前给 foo.do_something 一个打印出其初始值的机会。同样, foo.do_something 需要等待 main.change_foo 更改值才能打印出更新的值。为了实现这一点,我们使用两个 'multiprocessing.event' 实例:

import multiprocessing
import ctypes
import time

class main:
    def __init__(self):
        self.foo_instance = foo()
        multiprocessing.process(target=self.foo_instance.do_something).start()

    def change_foo(self):
        # wait for foo.do_something to have printed out its initial value:
        self.foo_instance.initial_print_event.wait()

        # modify the attribute (add missing self):
        self.foo_instance.importantvar.value = true

        # show that we have modified the attribute:
        self.foo_instance.changed_event.set()


class foo:
    def __init__(self):
        self.importantvar = multiprocessing.value(ctypes.c_bool, false, lock=false)
        self.initial_print_event = multiprocessing.event()
        self.changed_event = multiprocessing.event()

    def do_something(self):
        print('do_something before:', self.importantvar.value)
        # show that we have completed printing our initial value:
        self.initial_print_event.set()

        # now wait for main.change_foo to have changed our variable:
        self.changed_event.wait()

        print('do_something after:', self.importantvar.value)


# required for windows:
if __name__ == '__main__':
    main_instance = main()
    main_instance.change_foo()

打印:

do_something before: False
do_something after: True
卓越飞翔博客
上一篇: Golang 程序中命令行参数未正确接受作为参数
下一篇: 使用 VSC:无法导入错误库
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏