我是python的初学者,我已经开始尝试使用python3.4。以下是我尝试进行多线程合并排序。但似乎当执行程序用完线程时,提交将阻塞(我知道这个设计开始时是错误的)。我的问题是,如果没有空闲线程可以从池中使用,是否存在继续使用当前线程的安全非阻塞替代方案。
from concurrent.futures.thread import ThreadPoolExecutor
def merge(left_slice, right_slice):
lindex = 0
rindex = 0
result = []
while lindex != len(left_slice) or rindex != len(right_slice):
if lindex == len(left_slice):
result = result + right_slice[rindex:len(right_slice)]
return result
elif rindex == len(right_slice):
result = result + left_slice[lindex:len(left_slice)]
return result
elif left_slice[lindex] < right_slice[rindex]:
result.append(left_slice[lindex])
lindex = lindex + 1
elif left_slice[lindex] > right_slice[rindex]:
result.append(right_slice[rindex])
rindex = rindex + 1
else:
result.append(right_slice[rindex])
rindex = rindex + 1
result.append(left_slice[lindex])
lindex = lindex + 1
return result
def sort(numbers):
"""merge sort"""
if len(numbers) == 1:
return numbers
left_slice = numbers[0:len(numbers)//2]
right_slice = numbers[len(numbers)//2:len(numbers)]
left_future = executor.submit(sort, left_slice)
right_future = executor.submit(sort, right_slice)
left_slice = left_future.result()
right_slice = right_future.result()
return merge(left_slice, right_slice)
if __name__ == '__main__':
import random
unsorted = random.sample(range(1000000), 10000 )
import time
print ("starting to sort...")
start = time.time();
with ThreadPoolExecutor(max_workers=5) as executor:
future = executor.submit(sort, unsorted)
print(future.result()[-5:])
print("done sorting: " + time.time() - start)