Home > Software engineering >  How to find minimal value in array using multithreading in Python
How to find minimal value in array using multithreading in Python

Time:11-16

So I have array like this:

matrix = [[1, 2],[3, 4],[5, 6]]

and I want the code to return 1 as It's a minimal value in this array. I know how to do it the simple way, but I have a hard time when I want to use mutlithreading. I tried this way:

import threading
matrix = [[1, 2],[3, 4],[5, 6]]
def min(n, **total):
    if matrix[n][0] <= matrix[n][1]:
        minThreads['minThreads'] = matrix[n][0]
    else:
        minThreads['minThreads'] = matrix[n][1]

minThreads = {"minThreads":0}
for i in range(len(matrix)):
    t = threading.Thread(target=min, args=(i,), kwargs=minThreads)
    t.start()
print(minThreads['minThreads'])

But it returns 5 instead of 1. Do you maybe have any ideas how to implement this ? Any help would be greatly appreciated!

CodePudding user response:

you write the lowest value of a row regardless it's value. in your case, last line run last, see 5 < 6, => writes 5 over the 3 that was written over the 1. you should add comparison to the min value.

    import threading
    matrix = [[1, 2],[3, 4],[5, 6]]
    def min(n, **total):
        if matrix[n][0] <= matrix[n][1]:
            if(matrix[n][0]<minThreads['minThreads']):
                minThreads['minThreads'] = matrix[n][0]
        else:
            if(matrix[n][1]<minThreads['minThreads']):
                minThreads['minThreads'] = matrix[n][1]
    
    minThreads = {"minThreads":matrix[0][0]}
    for i in range(len(matrix)):
        t = threading.Thread(target=min, args=(i,), kwargs=minThreads)
        print('thread ',i)
        t.start()
    print(minThreads['minThreads'])
  • Related