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 中进程之间不共享实例变量的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题

Linux终端中查看Python版本时遇到权限问题的解决方法当你在Linux终端中尝试查看Python的版本时,输入python...

在使用Python的pandas库时,如何在两个结构不同的DataFrame之间进行整列复制是一个常见的问题。假设我们有两个Dat...

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...

本文讨论了诸如Numpy,Pandas,Matplotlib,Scikit-Learn,Tensorflow,Tensorflow,Django,Blask和请求等流行的Python库,并详细介绍了它们在科学计算,数据分析,可视化,机器学习,网络开发和H中的用途

Uvicorn是如何持续监听HTTP请求的?Uvicorn是一个基于ASGI的轻量级Web服务器,其核心功能之一便是监听HTTP请求并进�...

在Python中,如何通过字符串动态创建对象并调用其方法?这是一个常见的编程需求,尤其在需要根据配置或运行...
