使用线程库的简单排序程序出现越界错误



我正在尝试进行两种排序。冒泡排序和插入排序在python中练习使用多线程。当单独运行每个线程时,一切都很好,但当我一个接一个地运行两个线程时,冒泡排序会得到一个列表越界错误。这让我很困惑,因为它自己工作,但不想与同时运行的其他线程一起工作。

Error: 
Traceback (most recent call last):
File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner
self.run()
File "/usr/lib/python3.7/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "test.py", line 21, in bubbleSortArray
if arr[x] < arr[y]:
IndexError: list index out of range
import threading
from tqdm import tqdm
import random

def insertionSortArray(arr):
# Simple Insertion sort to start out

for x in tqdm(range(len(arr))):
for y in range(x):
if arr[x] < arr[y]:
arr.insert(y, arr[x])
del arr[x + 1]
break
print(arr)
def bubbleSortArray(arr):
# Simple Bubble sort to start out

for x in tqdm(range(len(arr))):
for y in range(len(arr)):
if arr[x] < arr[y]:
temp = arr[x]
arr[x] = arr[y]
arr[y] = temp
print(arr)

def generateArray(size):

return [random.randrange(0, 10000) for x in range(size)]

#generating the array for the thread functions
array = generateArray(10000)

bubble = threading.Thread(target = bubbleSortArray, args=[array])
insertion = threading.Thread(target = insertionSortArray, args=[array])

bubble.start()
insertion.start()

解决方案是不向两个线程传递相同的数组对象。复制一份。

还要使用tqdmposition参数来处理线程。

import threading
import random
import time
import tqdm
def insertionSortArray(arr):
# Simple Insertion sort to start out
with tqdm.tqdm(desc=f'InsertionSort', total=len(arr), position=1) as bar:
for x in range(len(arr)):
for y in range(x):
if arr[x] < arr[y]:
arr.insert(y, arr[x])
del arr[x + 1]
break
bar.update(1)
def bubbleSortArray(arr):
# Simple Bubble sort to start out
with tqdm.tqdm(desc=f'BubbleSort   ', total=len(arr), position=0) as bar:
for x in range(len(arr)):
for y in range(len(arr)):
if arr[x] < arr[y]:
temp = arr[x]
arr[x] = arr[y]
arr[y] = temp
bar.update(1)

def generateArray(size):
return [random.randrange(0, 10000) for x in range(size)]
#generating the array for the thread functions
array1 = generateArray(10000)
array2 = array1.copy() # Make a copy of the random list.
bubble = threading.Thread(target = bubbleSortArray, args=[array1])
insertion = threading.Thread(target = insertionSortArray, args=[array2])
bubble.start()
insertion.start()
bubble.join()
insertion.join()
# Check results
assert array1 == sorted(array1)
assert array1 == array2

输出:

InsertionSort: 100%|███████████████████████████████████████████████████████████| 10000/10000 [00:02<00:00, 4007.63it/s]
BubbleSort   : 100%|███████████████████████████████████████████████████████████| 10000/10000 [00:07<00:00, 1426.69it/s]

如果.copy()被移除:

C:>py test.py
InsertionSort:   0%|                                                                         | 0/10000 [00:00<?, ?it/s]Exception in thread Thread-1:                                                                 | 0/10000 [00:00<?, ?it/s]
Traceback (most recent call last):
File "C:Python38libthreading.py", line 932, in _bootstrap_inner
self.run()
File "C:Python38libthreading.py", line 870, in run
InsertionSort:  43%|█████████████████████████▍                                 | 4314/10000 [00:00<00:00, 42714.45it/s]    self._target(*self._args, **self._kwargs)
File "C:test.py", line 29, in bubbleSortArray
if arr[x] < arr[y]:
IndexError: list index out of range
Traceback (most recent call last):
File "C:test.py", line 51, in <module>
assert array1 == sorted(array1)
AssertionError

最新更新