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

2024-05-16 10:58:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着做两件事。冒泡排序和插入排序,以练习在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()

Tags: inpyselftargetforlineargsrange
1条回答
网友
1楼 · 发布于 2024-05-16 10:58:12

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

还可以使用position参数tqdm来处理线程

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:\Python38\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "C:\Python38\lib\threading.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

相关问题 更多 >