gpt4 book ai didi

python - Python Thread()删除换行符?

转载 作者:行者123 更新时间:2023-12-03 13:16:36 27 4
gpt4 key购买 nike

我在程序中遇到了一个特殊的错误。该代码背后的一般思想是,首先创建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()
输出不正确,在打印语句3和4之间换行符似乎消失了:
The mean value of the list number 1 is 5270.34
The time taken to find it was 0.00012170000000000236 seconds.

The mean value of the list number 2 is 4768.17
The time taken to find it was 9.239999999999943e-05 seconds.

The mean value of the list number 3 is 4766.67
The time taken to find it was 8.369999999999905e-05 seconds.
The mean value of the list number 4 is 4969.7
The time taken to find it was 9.880000000000305e-05 seconds.


The mean value of the list number 5 is 4686.21
The time taken to find it was 9.25000000000023e-05 seconds.

最佳答案

正在换行。请注意,语句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.
)

关于python - Python Thread()删除换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63431140/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com