为什么这个线程不重启?

时间:2019-09-17 19:10:43

标签: python python-multithreading

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

在下面的示例代码中,我首先通过函数调用启动myThread。然后,我暂停片刻(for循环),以使myThread在停止之前运行。接下来,我再次调用该函数以重新启动myThread(由于它是一个新实例,因此实际上不是重新启动),但是从输出中可以看到,它永远不会重新启动。它也不会引发可怕的“ RuntimeError:线程只能启动一次”异常,因此我知道我不会走这条路。我已经简化了此代码示例的实际操作,其行为方式与我的实际代码相同。

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

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

1 个答案:

答案 0 :(得分:1)

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")