Skip to content

Instantly share code, notes, and snippets.

@hasanparasteh
Created December 4, 2021 05:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hasanparasteh/6ada7ba47303940a90d3da9c90bf547f to your computer and use it in GitHub Desktop.
Save hasanparasteh/6ada7ba47303940a90d3da9c90bf547f to your computer and use it in GitHub Desktop.
Calculate summation of each row and whole matrix in parallel
import multiprocessing as mp
import random
from typing import List
class ParallelSummation:
def __init__(self) -> None:
self.matrix: List = []
def randomize_matrix(self, n: int, m: int) -> List:
for row in range(n):
self.matrix.append([random.randint(0, 100) for _ in range(m)])
print("Matrix:", self.matrix)
def summation(self, row: List, result) -> int:
"""
Summation of all elements each row of matrix
"""
sum: int = 0
for element in row:
sum += element
result.put(sum)
def create_process(self, matrix: List) -> List:
process_list: List = []
for row in range(len(matrix)):
mp.set_start_method('fork', force=True)
q = mp.Queue()
p = mp.Process(target=self.summation, args=(matrix[row], q))
process_list.append({"process": p, "queue": q})
return process_list
def run(self):
sum = 0
process_list: List = self.create_process(self.matrix)
for item in process_list:
item["process"].start()
for item in process_list:
item["process"].join()
result = item["queue"].get()
print("Summation of row {} is {}".format(
process_list.index(item), result))
sum += result
print("Summation of all rows is {}".format(sum))
if __name__ == '__main__':
summation = ParallelSummation()
summation.randomize_matrix(100, 10)
summation.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment