我在我的程序中遇到了一个特殊的错误。代码背后的总体思路是首先创建一个包含 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条经验 获得超3个赞
正在打印换行符。请注意,在语句 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
提交
取消