Reputation: 501
I'm trying to change 'double for loop' to 'for + multiprocessing' in python.
(I cannot come up with an idea for change double for loop to one multiprocessing code, not for + multiprocessing)
functiona gives different results for different i and j (first and second for loop)
I changed second loop(j) to multiprocessing.Pool() and it works.
However if I use first for loop with second loop(multiprocessing), in functiona the index of first loop does not change.
If I run code below, multiprocessing works, however the y in functiona does not change.
I tried to use global, it does not work. What should I do?
from multiprocessing import Pool
import multiprocessing
y = 0
def functiona(i):
# global y
print('y', y, i)
if __name__=='__main__':
start_time = datetime.now()
pool = multiprocessing.Pool() # pool = Pool(processes=16)
for t in range(0, 10):
print('t : ', t)
y = t
result = pool.map(functiona, range(0, 10))
print("- %s seconds -" % (datetime.now() - start_time))
Upvotes: 0
Views: 98
Reputation: 710
Is this what you trying to achieve?:
import multiprocessing
from datetime import datetime
y = 0
def functiona(i,y):
# global y
print('y', y, i)
if __name__=='__main__':
start_time = datetime.now()
pool = multiprocessing.Pool() # pool = Pool(processes=16)
functiona_args = []
for t in range(0, 10):
print('t : ', t)
y = t
for i in range(0,10):
functiona_args.append((i,y,))
result = pool.starmap(functiona, functiona_args)
Upvotes: 1