并行运行的对象的方法看不到对属性的更改



>我得到了一个带有两个主体函数的对象: 1)一个是"扫描",当找到感兴趣的内容时,将其添加到当前对象的属性列表中。 2)第二个对列表中找到和存储的内容进行操作。 我希望第一个函数运行很长时间,就像在后台一样,第二个函数处理存储的内容。所以我尝试使用多线程。

但是当我的第一个函数修改列表时,第二个函数看不到修改。下面是最小示例。

这是最小的例子。

# coding: utf-8
import numpy as npy
import time
from multiprocessing import Process, RLock
class MyStruct(object):
def __init__(self):
self.listOfInterest = []
def searching(self):
while True:
time.sleep(2) # unelegant way to be sure that one process doesn't block other one from running
a = npy.random.randn(1)[0] # random way to add something to the list
if a>=0:
self.listOfInterest.append(a)
print(' add ',str(a),' to list ')
def doingStuff(self):
while True:
time.sleep(1) 
try:
a = self.listOfInterest[0] # pb here : list allways empty for this function
# doing stuff on a we don't care here
except IndexError:
print(' list still empty, nothing to deal with ')
if __name__=='__main__':
mystruct = MyStruct()
p1 = Process(target=mystruct.searching)
p2 = Process(target=mystruct.doingStuff)
p1.start()
p2.start()
p1.join()
p2.join()

在我的问题中评论"跳"之后,答案很容易。只需要使用线程而不是进程。

在维基百科上看了一下,在第一个和粗略的近似中,我们可以说线程和进程都是指令列表,但线程共享记忆。

如果我们想更精确(如果我们尝试...),以下是有问题的代码中发生的情况:

1)我们运行命令"python3 MyStruct.py",内核启动一个进程,我们称之为P。这个过程获得它的内存,并在某个部分存储一个由python构建的对象mystruct

2)当P运行命令p1.start()和p2.start()时,它会产生我们所说的fork。就像生物细胞分裂成两个细胞一样,它变成了两个过程,我们称之为P1和P2,它们中的每一个都独立于另一个。他们每个人都得到一个对象的副本,并对其进行处理。因此,当一个修改 listOfInterest 时,它在对象上是自己的进程内存,所以另一个看不到它。

如果我们使用线程而不是进程,进程 P 运行两个线程,它们是它的一部分,它们将共享内存。

这里是修改代码

import numpy as npy
import time
from threading import Thread
class MyStruct(object):
def __init__(self):
self.listOfInterest = []
def searching(self):
while True:
time.sleep(2) # unelegant way to be sure that one process doesn't block other one from running
a = npy.random.randn(1)[0] # random way to add something to the list
if a>=0:
self.listOfInterest.append(a)
print(' add ',str(a),' to list ')
def doingStuff(self):
while True:
time.sleep(1) 
try:
a = self.listOfInterest[0] # pb here : list allways empty for this function
# doing stuff on a we don't care here
except IndexError:
print(' list still empty, nothing to deal with ')
if __name__=='__main__':
mystruct = MyStruct()
p1 = Thread(target=mystruct.searching)
p2 = Thread(target=mystruct.doingStuff)
p1.start()
p2.start()
p1.join()
p2.join()

最新更新