在start_thread
方法中启动的线程不会停止。为什么?
import time
import threading
cont_running = True
def start_thread():
threading.Thread(target=run).start()
def stop_thread():
cont_running = False
def run():
while cont_running:
print 'Thread running : ' + str(cont_running)
time.sleep(0.2)
print 'Thread ended'
start_thread()
time.sleep(2)
stop_thread()
答案 0 :(得分:4)
在stop_thread()
中,您的赋值语句会创建一个名为cont_running
的局部变量。此局部变量与同名的全局变量无关。
试试这个:
def stop_thread():
global cont_running
cont_running = False