Как распараллелить доступ к общему массиву в Python с помощью concurrent.futures?Python

Программы на Python
Anonymous
Как распараллелить доступ к общему массиву в Python с помощью concurrent.futures?

Сообщение Anonymous »

У меня есть следующий фрагмент кода, иллюстрирующий мою проблему:
Каждый поток вычисляет локальные значения, а затем обновляет массив результатов. Предположим, что это обновлять (result[locs] += mask[locs] ) — очень медленная операция, как ее распараллелить, чтобы можно было использовать многопоточность?
import numpy as np
import time
import concurrent.futures

MAX = 100
SIZE = 500
mask = np.random.randint(0, MAX, (SIZE, SIZE))

def process_image(i):
start = time.time()
locs = np.where(mask > i)
print(f" process_image({i}) took {round(time.time() - start, 2)} secs.")
return locs

if __name__ == '__main__':

result = np.zeros((SIZE, SIZE))

with concurrent.futures.ThreadPoolExecutor(max_workers=32) as executor:
results = [executor.submit(process_image, i) for i in range(MAX) ]
for f in concurrent.futures.as_completed(results):
locs = f.result()
# How do I parallelize this operation? Where the result of each thread updates a shared result array
result[locs] += mask[locs]

print(result)


Подробнее здесь: https://stackoverflow.com/questions/785 ... rent-futur

Вернуться в «Python»