为什么这个线程不会重新启动?

Why won't this thread restart?

我有一个我写的程序,我试图停止然后重新启动线程函数。我知道线程的实例只能使用一次,但由于线程是从函数调用的,而且它不是全局变量,据我所知,它本质上是一个新变量被声明。

在下面的示例代码中,我首先通过函数调用启动 myThread。然后我暂停片刻(for 循环)让 myThread 在我停止它之前得到 运行。接下来,我再次调用该函数以重新启动 myThread(不是真正的重新启动,因为它是一个新实例)但它永远不会重新启动,正如您在输出中看到的那样。它也不会抛出可怕的 "RuntimeError: threads can only be started once" 异常,所以我知道我不会走那条路。我已经简化了我使用此代码示例实际执行的操作,它的行为方式与我的实际代码相同。

#test-thread.py

import os, threading

stopThread = False
option = ''

def threaded_function():

    global option, stopThread

    n = 0
    while not stopThread:
        n += 1
        if option == "started":
            print ("myThread is running ("+str(n)+")\n")
        if option == "restarted":
            print ("myThread is running again ("+str(n)+")\n")

def thread_control_function():

    global stopThread

    print ("Entered the thread_control function\n")
    if option == "started":
        print ("Starting myThread\n")
        myThread = threading.Thread(target=threaded_function)
        myThread.start()
        print("Started myThread\n")
    elif  option == "restarted":
        print("restarting myThread\n")
        myThread = threading.Thread(target=threaded_function)
        myThread.start()
        print("restarted myThread\n")
    elif option == "stopped":
        print ("Stopping myThread\n")
        stopThread = True
        print ("myThread is stopped\n")
    print ("Exiting the thread_control function\n")

# Clear the python console
os.system("clear")

option = "started"
thread_control_function()

for i in range(1,200000):
    pass

option = "stopped"
thread_control_function()

for i in range(1,200000):
    pass

option = "restarted"
thread_control_function()

for i in range(1,200000):
    pass

option = "stopped"
thread_control_function()

在我正在处理的主程序中,我有一个停止游戏按钮,当我单击停止游戏按钮时,它会将 stopThread 变量设置为 true。 它实际上停止了游戏并重置了所有游戏变量。我可以单击“开始游戏”按钮,它的行为与我预期的一样(开始新游戏)。我正在尝试使用将 stopThread 设置为 true 的重启按钮,不重置所有游戏变量,然后我启动(重启)游戏线程。我不明白为什么这不能启动另一个线程(重新启动)。

stopThread 标志从未重置。 thread_control_function 应如下所示:

def thread_control_function():

    global stopThread

    print ("Entered the thread_control function\n")
    if option == "started":
        print ("Starting myThread\n")
        myThread = threading.Thread(target=threaded_function)
        myThread.start()
        print("Started myThread\n")
    elif  option == "restarted":
        print("restarting myThread\n")
        stopThread = False
        myThread = threading.Thread(target=threaded_function)
        myThread.start()
        print("restarted myThread\n")
    elif option == "stopped":
        print ("Stopping myThread\n")
        stopThread = True
        print ("myThread is stopped\n")
    print ("Exiting the thread_control function\n")