我怎么确定这段代码是线程安全的?
import numpy as np
from threading import Thread
n_threads = 5
ones = np.ones((5, 5))
A = np.ones((5, 5))
def my_function():
global A
for i in range(250):
A += ones # is += thread safe ?
threads = [Thread(target=my_function) for i in range(n_threads)]
for t in threads:
t.start()
for t in threads:
t.join()
print(A)
是否应该将A设为关键共享内存?令人惊讶的是,我总是得到相同的结果,并且数组的所有条目都具有相同的值。我原本期望线程会更新矩阵的值,但实际上可能会有一些值丢失...
谢谢。
a+=a[0]
,则a[0]
可能会随着您的操作而改变。 - DYZ