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

Thead.join() not helping in printing a string only after all the threads are finished

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

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

我的困惑源于这样一个事实,即 .join() 方法非常适合类似的功能。仅在所有线程完成后才打印字符串。它们之间的主要区别在于另一个函数不接受任何随机输入。相反,它遍历一个名为 'messages_and_times' 的全局字典,其中 key:value 对来自用户输入的消息和秒数(用户输入由另一个函数处理)。

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

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

提前感谢您的宝贵时间和协助。

P.S。 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 的建议,以下是我如何修改我的函数以按预期工作。我希望这有助于将来浏览解决方案的人。

Option_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()

Option_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 对象)所以加入函数 returns 当最后一个线程完成,程序继续。

即使在选项 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()