问题
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.
Here is what I have tried.
from threading import Thread
import threading
import time
import thread
def qsort(sets,left,right):
i = left
j = right
pivot = sets[(left + right)/2]
temp = 0
while(i <= j):
while(pivot > sets[i]):
i = i+1
while(pivot < sets[j]):
j = j-1
if(i <= j):
temp = sets[i]
sets[i] = sets[j]
sets[j] = temp
i = i + 1
j = j - 1
if (left < j):
thread = Thread(target = qsort(sets,left,j))
name = threading.current_thread()
printp(sets,elements,name)
if (i < right):
thread1 = Thread(target=qsort(sets,i,right))
name = threading.current_thread()
printp(sets,elements,name)
return sets
回答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
def qsort(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 = 0
while(i <= j):
while(pivot > sets[i]):
i = i+1
while(pivot < sets[j]):
j = j-1
if(i <= j):
temp = sets[i]
sets[i] = sets[j]
sets[j] = temp
i = i + 1
j = j - 1
lthread = None
rthread = None
if (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 is not None: lthread.join()
if rthread is not None: 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]
回答2:
There is no reel parallel execution with threads in Python. Use Pool or Processs. fork is still possible. Alex
来源:https://stackoverflow.com/questions/36595838/concurrent-quick-sort-multithreading