I want to find some of the solutions of the Pythagorean relation using multiprocessing module in python in the following snippet. To speed up the process of finding the answers, I am trying to parallelize the process:
import itertools
from multiprocessing import Pool, Array
import numpy as np
MAXIMUM_INT: int = 10
answers = {'A': [], 'B': [], 'C': []}
base_range = np.arange(1, MAXIMUM_INT + 1)
A_range = B_range = C_range = base_range.tolist()
combinatorics = [A_range, B_range, C_range]
iteration = list(itertools.product(*combinatorics))
dim1 = dim2 = dim3 = MAXIMUM_INT
def init(A: int, B: int, C: int):
global test1, test2, test3
test1, test2, test3 = A, B, C
def conditionalAssert(answerDict: dict, A: int, B: int, C: int):
t1 = np.frombuffer(test1.get_obj())
t2 = np.frombuffer(test2.get_obj())
t3 = np.frombuffer(test3.get_obj())
if A**2 + B**2 == C**2:
answerDict['A'].append(t1)
answerDict['B'].append(t2)
answerDict['C'].append(t3)
if __name__ == '__main__':
relevantArray = Array('i', dim1 * dim2 * dim3)
A = B = C = relevantArray
pool = Pool(processes=7, initializer=init, initargs=(A, B, C))
pool.starmap(conditionalAssert, iteration)
print(answers)
However, running the script "as is" creates an error that I don't know how to solve. I would appreciate any help:
multiprocessing.pool.RemoteTraceback:
"""
Traceback (most recent call last):
File "C:\Users\username\anaconda3\Lib\multiprocessing\pool.py", line 125, in worker
result = (True, func(*args, **kwds))
^^^^^^^^^^^^^^^^^^^
File "C:\Users\username\anaconda3\Lib\multiprocessing\pool.py", line 51, in starmapstar
return list(itertools.starmap(args[0], args[1]))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: conditionalAssert() missing 1 required positional argument: 'C'
"""
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "c:\Users\username\OneDrive\Desktop\Projects\pythagorean.py", line 38, in <module>
pool.starmap(conditionalAssert, iteration)
File "C:\Users\username\anaconda3\Lib\multiprocessing\pool.py", line 375, in starmap
return self._map_async(func, iterable, starmapstar, chunksize).get()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\username\anaconda3\Lib\multiprocessing\pool.py", line 774, in get
raise self._value
TypeError: conditionalAssert() missing 1 required positional argument: 'C'
A**2 + B**2 == C**2, i'm not sure ifmultiprocessingis the right approach here.iterationgenerates tuple of 3 elements, but your functionconditionalAssertexpect 4 parameters. Thus you get the error that the last parameterCis missing.answerDict: dictfrom the parameter list and insteadconditionalAssertshould return an object. In the__name__ == '__main__'you get all these objects from.starmapand construct the final one. Another approach is using docs.python.org/3/library/multiprocessing.shared_memory.html