gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:15:42 25 4
gpt4 key购买 nike

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

在下面的示例代码中,我首先通过函数调用启动 myThread。然后我暂停一会儿(for 循环),让 myThread 在停止之前运行。接下来,我再次调用该函数来重新启动 myThread(并不是真正的重新启动,因为它是一个新实例),但正如您在输出中看到的那样,它永远不会重新启动。它也不会抛出可怕的“运行时错误:线程只能启动一次”异常,所以我知道我不会走那条路。我已经简化了我对此代码示例的实际操作,其行为方式与我的实际代码相同。

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

关于python - 为什么这个线程不会重新启动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57980639/

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