作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
那么为什么在下面的示例中永远不会打印“YES”?我需要访问self.stuff
类one()
来自类(class)two()
,然而self.one.stuff
上课two()
即使我在类 one()
中添加到它之后,也总是打印一个空字典.
import threading
import time
from multiprocessing import Process
class one():
def __init__(self):
self.stuff = {}
self.two = two(self)
def start(self):
while True:
print "Process Loop"
time.sleep(2)
self.stuff['hi'] = 1
print self.stuff
class two():
def __init__(self, o):
self.one = o
self.thread = threading.Thread(target=self.doit, args=())
self.thread.setDaemon(True)
self.thread.start()
def doit(self):
print "Thread Loop"
while True:
if 'hi' in self.one.stuff:
print "YES"
time.sleep(3)
ooo = one()
p = Process(target=ooo.start)
p.start()
这会导致
Thread Loop
Process Loop
{'hi': 1}
Process Loop
{'hi': 1}
Process Loop
{'hi': 1}
Process Loop
{'hi': 1}
Process Loop
如果我不将 one() 作为进程启动,则输出将如我所期望的那样:
ooo = one()
ooo.start()
Process Loop
Thread Loop
{'hi': 1}
Process Loop
YES
{'hi': 1}
Process Loop
YES
{'hi': 1}
Process Loop
最佳答案
当您创建 one
实例时,它是在主进程中创建的。这意味着在主进程中,two
实例已经创建,并且它的 doit
线程已经启动。
当您在子进程中运行 ooo.start
时,它不再有权访问原始 two
实例,反之亦然 - 新进程拥有每个实例的副本实例,但子进程中的 two
实例没有执行任何操作,主进程中的 one
实例也没有执行任何操作。
简而言之:@juanpa.arrivallaga 的评论就是答案 - 进程不共享状态。
关于python - 线程和进程之间的范围问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48511429/
我是一名优秀的程序员,十分优秀!