python速学教程(入门到精通)
python怎么学习?python怎么入门?python在哪学?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
可以修改 foo
的 importantvar
属性,我们必须在 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
Python免费学习笔记(深入):立即学习
在学习笔记中,你将探索 Python 的核心概念和高级技巧!
已抢7337个
抢已抢95475个
抢已抢14940个
抢已抢52729个
抢已抢195932个
抢已抢87512个
抢