How can I be sure this code is thread safe ?
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)
Should A be a critical shared memory ? Surprisingly I always get the same result, and all entries of the array all have the same value. I would expect for the threads to update the values of the matrix, and for some to be lost...
Thanks.
a+=a[0], thea[0]may change as you go.+=is not useful if you expect to add values repeatedly to an indexed value. It uses a buffer. Seeadd.atfor an unbuffered version.