考虑下面的代码,其中我替换了一个类变量(numpy数组)的值。为什么m.mydict的值没有改变?
from threading import Thread, Lock
import numpy as np
class MyClass(object):
def __init__(self):
#self.var = np.array([1, 2, 3, 4, 5])
self.mydict = {'a1': None,
'a2': None}
self.lock = Lock()
def mythread(self, arg1, arg2):
self.lock.acquire()
b = np.array([9,9,9])
arg2 = b
self.lock.release()
def test(self, condition):
if condition:
Thread(target=self.mythread, args=(0, self.mydict['a1'])).start()
else:
Thread(target=self.mythread, args=(0, self.mydict['a2'])).start()
m = MyClass()
m.test(True)
print(m.mydict)
>>> {'a1': None, 'a2': None}
当您的线程直接访问实例self
时,通过引用传递self.var
(或其他实例属性)是没有意义的:
class MyClass(object):
...
def mythread(self, arg1):
b = np.array([9, 9, 9, 9, 9])
self.lock.acquire()
self.var = b
self.lock.release()
def test(self):
Thread(target=self.mythread, args=(0,)).start()
m = MyClass()
m.test()
print(m.var)
[9 9 9 9 9]
和你的第二个版本一样,设计得很差。下面是修复方法:
class MyClass(object):
def __init__(self):
# self.var = np.array([1, 2, 3, 4, 5])
self.mydict = {'a1': None, 'a2': None}
self.lock = Lock()
def mythread(self, arg1, key):
self.lock.acquire()
b = np.array([9, 9, 9])
self.mydict[key] = b
self.lock.release()
def test(self, condition):
if condition:
Thread(target=self.mythread, args=(0, 'a1')).start()
else:
Thread(target=self.mythread, args=(0, 'a2')).start()
m = MyClass()
m.test(True)
print(m.mydict)
{'a1': array([9, 9, 9]), 'a2': None}