并发快速排序(多线程)

时间:2016-04-13 10:37:50

标签: python multithreading quicksort

我正在尝试使用threading快速排序并发。但是当我使用我的线程方法运行代码时,它只会递归地为所有分区运行相同的线程。

这是我尝试过的。

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

2 个答案:

答案 0 :(得分:2)

(除了@bereal在问题评论中指出的问题)你看到的问题的根本原因(它们都在同一个线程中运行)是你误用了{{3的第二个参数“target”这应该是一个可调用的对象。

以下是固定代码:

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)

输出:

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]

答案 1 :(得分:1)

Python中的线程没有卷轴并行执行。使用池或进程。叉子仍然可以。 亚历