【发布时间】:2016-04-13 10:37:50
【问题描述】:
我正在尝试使用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
【问题讨论】:
-
首先,您不会启动任何已创建的线程。其次(实际上应该是第一个),由于臭名昭著的GIL,在 Python 中,多线程不会给您带来任何性能提升。
-
我也使用了 thread.start()。没有成功。
-
回到你因为 GIL 而没有在 python 中使用多线程的原因。我真的不在乎,因为我在 5 天内有一个实用程序,并且问题陈述是并发快速排序。
-
所以我应该使用多进程而不是多线程吗?
-
嗯,首先你当然可以让它与线程一起工作,尽管没有看到你如何启动线程并等待它们完成,所以很难提出任何建议。
标签: python multithreading quicksort