gpt4 book ai didi

python - Thead.join() 仅在所有线程完成后才帮助打印字符串

转载 作者:行者123 更新时间:2023-12-01 08:18:31 26 4
gpt4 key购买 nike

我目前正在尝试编写一个实现以下功能的函数:

  • 按随机顺序从“消息”列表中获取所有消息,同时确保没有重复的消息。
  • 在延迟 1 - 10 秒范围内的随机秒数后打印它们。
  • 所有线程完成后,打印字符串“打印完成,5秒后返回主菜单。”

然而,我遇到的问题是字符串“Printing is finish...”是在随机消息之间打印的,而不是在它们之后。

我的困惑源于这样一个事实:.join() 方法对于类似的函数来说完美无缺。仅在所有线程完成后才打印该字符串。它们之间的主要区别在于另一个函数不接受任何随机输入。相反,它会迭代一个名为“messages_and_times”的全局字典,其中键:值对来自用户输入的消息和秒数(用户输入由另一个函数处理)。

下面您可以看到函数 option_3() 不起作用,而函数 option_2() 起作用。在最底部我将包含整个代码以供进一步引用。

有人可以帮我理解我做错了什么吗?

预先感谢您的时间和帮助。

附注clear() 函数用于在每次输入后清除终端显示。

非工作功能:

def option_3():
clear()
messages = ["message_1", "message_2", "message_3", "message_4", "message_5",
"message_6", "message_7", "message_8", "message_9", "message_10"]

print("Printing initialized:\n")

def threading_function(message, seconds):
time.sleep(seconds)
print(message)

for message in messages:
randomized_messages = []
random_index = random.randint(0, len(messages) - 1)
randomized_messages.append(messages.pop(random_index))
for msg in randomized_messages:
t = Thread(target=threading_function, args=(msg, random.choice(range(1,11))))
t.start()


t.join()
time.sleep(0.5)
print(
"\nPrinting is finished. You will be returned to the main menu in 5 seconds.")
time.sleep(5)
main_menu()
<小时/>

工作功能:

def option_2():
global messages_and_times

clear()
print("Printing initialized:\n")

def threading_function(message, seconds):
time.sleep(seconds)
print(message)

for message, seconds in messages_and_times.items():
t = Thread(target=threading_function, args=(message, seconds))
t.start()

t.join()
time.sleep(0.5)
print(
"\nPrinting is finished. You will be returned to the main menu in 5 seconds.")
time.sleep(5)
main_menu()
<小时/>

整个 main_menu() 函数:

import os
import random
clear = lambda: os.system('cls')

messages_and_times = {}


def main_menu():

def option_1():
global messages_and_times

clear()
message = input(
"Please type in a message you would like to add to the list:")
clear()
seconds = int(
input("Please type in the time of delay for this message:"))
messages_and_times[message] = seconds

def create_dictionary():

clear()
answer = input(
"Would you like to add another message? (yes/no)").lower()
if answer == "yes":
option_1()
elif answer == "no":
clear()
print("You will now be returned to the main menu.")
time.sleep(1.5)
main_menu()
else:
clear()
print("Please answer yes or no.")
time.sleep(1.5)
create_dictionary()
create_dictionary()

def option_2():
global messages_and_times

clear()
print("Printing initialized:\n")

def threading_function(message, seconds):
time.sleep(seconds)
print(message)

for message, seconds in messages_and_times.items():
t = Thread(target=threading_function, args=(message, seconds))
t.start()

t.join()
time.sleep(0.5)
print(
"\nPrinting is finished. You will be returned to the main menu in 5 seconds.")
time.sleep(5)
main_menu()

def option_3():
clear()
messages = ["message_1", "message_2", "message_3", "message_4", "message_5",
"message_6", "message_7", "message_8", "message_9", "message_10"]
randomized_messages = []
print("Printing initialized:\n")

def threading_function(message, seconds):
time.sleep(seconds)
print(message)

for message in messages:
random_index = random.randint(0, len(messages) - 1)
randomized_messages.append(messages.pop(random_index))
for msg in randomized_messages:
t = Thread(target=threading_function, args=(msg, random.choice(range(1,11))))
t.start()


t.join()
time.sleep(0.5)
print(
"\nPrinting is finished. You will be returned to the main menu in 5 seconds.")
time.sleep(5)
main_menu()


clear()
selection = 0
while selection == 0:
print(("-" * 15) + "MAIN MENU" + ("-" * 15) + "\n")
print("1: Input a message and a corresponding time of delay before its display.")
print("2: Print your customized list of messages.")
print("3: Print random messages with random delays.\n")

selection = int(input(
"Please select one of the options, by typing in the corresponding number:"))

if selection == 1:
option_1()
elif selection == 2:
option_2()
elif selection == 3:
option_3()
else:
clear()
print("Please select from options 1 - 3.\n")
time.sleep(1.5)
main_menu()

编辑(最终解决方案供将来引用):

感谢 Almog David 的建议,以下是我修改函数以使其按预期工作的方法。我希望这对将来寻找解决方案的人有所帮助。

选项_2():

 def option_2():
global messages_and_times

clear()
threads = []
print("Printing initialized:\n")

def threading_function(message, seconds):
time.sleep(seconds)
print(message)

for message, seconds in messages_and_times.items():
t = Thread(target=threading_function, args=(message, seconds))
t.start()
threads.append(t)

for t in threads:
t.join()

time.sleep(0.5)
print(
"\nPrinting is finished. You will be returned to the main menu in 5 seconds.")
time.sleep(5)
main_menu()

选项_3():

def option_3():
clear()
messages = ["message_1", "message_2", "message_3", "message_4", "message_5",
"message_6", "message_7", "message_8", "message_9", "message_10"]
threads = []
print("Printing initialized:\n")

def threading_function(message, seconds):
time.sleep(seconds)
print(message)

for message in messages:
t = Thread(target=threading_function, args=(
message, random.choice(range(1, 11))))
t.start()
threads.append(t)
for t in threads:
t.join()

time.sleep(0.5)
print(
"\nPrinting is finished. You will be returned to the main menu in 5 seconds.")
time.sleep(5)
main_menu()

最佳答案

问题是您只等待最后一个线程加入(因为循环结束时“t”变量保存着最后创建的 Thread 对象),因此当最后一个线程完成并且程序继续时,join 函数返回。

即使在选项 2 上,我也能够通过提供以下内容重现此错误:

messages_and_times = {"message_0": 3,
"message_1": 3,
"message_2": 1}

上述配置的结果是:

message_2

Printing is finished. You will be returned to the main menu in 5 seconds.
message_0
message_1

您应该采取的措施来修复它:

threads = []

for message, seconds in messages_and_times.items():
t = Thread(target=threading_function, args=(message, seconds))
t.start()
threads.append(t)

for t in threads:
t.join()

关于python - Thead.join() 仅在所有线程完成后才帮助打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54843169/

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