我在我的程序中遇到了一個特殊的錯誤。代碼背后的總體思路是首先創建一個包含 5 個列表的數組(稱為 lists_of_nums)。每個列表由 1 到 10000 范圍內的 100 個數字組成。程序然后運行 5 個線程。每個人都找到一個列表的平均值,并打印出完成它所花費的時間。您會注意到在 threading_function() 中的 print() 語句的末尾有一個換行符。就在它說“seconds.\n”的地方。問題是,如果我將 't.join()' 放在一個單獨的 'for' 循環中(在我的代碼的最底部),為了同時運行線程,換行符有時會被刪除(顯然)。如果我一個一個地單獨運行線程,它只能在 100% 的時間內工作。我希望有人可以幫助我了解如何同時運行線程并且仍然讓換行符可靠。讓我用代碼示例及其不正確的輸出(僅在某些時候發生)來說明我的意思:lists_of_nums = []def create_set(): # Function for creating a list of random integers and appending them to the lists_of_nums array. random_nums = [] for _ in range(100): random_nums.append(randint(1, 10000)) lists_of_nums.append(random_nums)for _ in range(5): # Five of these lists get appended to the array, by using the create_set() function. create_set()def threading_function(list_index): # Function responsible for finding the mean value of a given list as well as the time taken to do it. start = timeit.default_timer() mean_value = mean(lists_of_nums[list_index]) end = timeit.default_timer() - start print( "The mean value of the list number " + str(list_index + 1) + " is " + str(mean_value) + "\nThe time taken to find it was " + str(end) + " seconds.\n" # The abovementioned newline. )threads = []for i in range(len(lists_of_nums)): t = Thread(target = threading_function, args = [i]) t.start() threads.append(t)for t in threads: # If t.join() remains in a separate 'for' loop than the Thread() class, the newline occasionally disappears. t.join()
2 回答

Helenr
TA貢獻1780條經驗 獲得超4個贊
正在打印換行符。請注意,在語句 4 和 5 之間有一條額外的線。您的線程之間可能存在競爭條件。嘗試print用鎖保護函數。IE,
printLock = threading.Lock() # global variable
進而
# inside threading_function
with printLock:
print(
"The mean value of the list number " + str(list_index + 1) + " is " + str(mean_value) +
"\nThe time taken to find it was " + str(end) + " seconds.\n" # The abovementioned newline.
)

慕俠2389804
TA貢獻1719條經驗 獲得超6個贊
字符串中的換行符完好無損。print
默認情況下會在之后添加一個換行符。它在單獨的寫入中執行此操作。來自不同線程的兩次寫入(原始字符串和換行符)可以交錯,因此有時您還會看到雙空行。如果從字符串中刪除換行符,您會看到類似的奇怪效果。
一種解決方案是在兩個換行符中結束您的字符串并停止print
添加自己的字符串,即print("....\n\n", end="")
.
添加回答
舉報
0/150
提交
取消