Skip to content Skip to sidebar Skip to footer

Concurrent Quick Sort (multithreading)

I am trying to make quick sort concurrent by using threading. But when i run the code with my threading approach, it only runs the same thread for all the partitions recursively. H

Solution 1:

(besides the issues @bereal pointed out in the comment under the question) The root cause to the problem that you saw (they all ran in the same thread) is that you misused the second argument "target" of class Thread, which should be a callable object.

Below is the fixed code:

from threading import Thread
import threading
import time
import thread

defqsort(sets,left,right):

    print("thead {0} is sorting {1}".format(threading.current_thread(), sets[left:right]))

    i = left
    j = right
    pivot = sets[(left + right)/2]
    temp = 0while(i <= j):
         while(pivot > sets[i]):
             i = i+1while(pivot < sets[j]):
             j = j-1if(i <= j):
             temp = sets[i]     
             sets[i] = sets[j]
             sets[j] = temp
             i = i + 1
             j = j - 1

    lthread = None
    rthread = Noneif (left < j):
        lthread = Thread(target = lambda: qsort(sets,left,j))
        lthread.start()

    if (i < right):
        rthread = Thread(target=lambda: qsort(sets,i,right))
        rthread.start()

    if lthread isnotNone: lthread.join()
    if rthread isnotNone: rthread.join()
    return sets


'''testing below'''
ls = [1,3,6,9,1,2,3,8,6]
res = qsort(ls, 0, len(ls) - 1)
print(res)

Output:

thead <_MainThread(MainThread, started 49900)> is sorting [1, 3, 6, 9, 1, 2, 3,8]thead <Thread(Thread-1, started 38136)> is sorting [3, 6, 9, 1, 2, 3, 8]thead <Thread(Thread-2, started 42024)> is sorting [6, 9, 3, 2, 3, 8]thead <Thread(Thread-3, started 36344)> is sorting [9, 3, 6, 3, 8]thead <Thread(Thread-4, started 47684)> is sorting [6, 3]thead <Thread(Thread-5, started 27760)> is sorting [6, 8][1, 1, 2, 3, 3, 6, 6, 8, 9]

Solution 2:

There is no reel parallel execution with threads in Python. Use Pool or Processs. fork is still possible. Alex

Post a Comment for "Concurrent Quick Sort (multithreading)"