只有在所有线程完成后,thead.join()才帮助打印字符串

时间:2019-02-23 15:33:54

标签: python python-3.x multithreading function delay

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

  • 以随机顺序从“邮件”列表中获取所有邮件,同时确保没有重复。
  • 在1到10秒之间的随机秒数延迟后打印它们。
  • 所有线程完成后,它会打印一个字符串“打印完成。您将在5秒钟内返回到主菜单。”

但是,我遇到的问题是,在随机消息之间而不是在消息之后打印了字符串“打印完成...”。

我的困惑源于以下事实:.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()

1 个答案:

答案 0 :(得分:1)

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

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

df_new = df1.merge(df2, on='timestamp', how='outer')
df_new = df_new.merge(d3, on='timestamp', how='outer')

以上配置的结果是:

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