线程为什么不停止?

时间:2017-05-03 18:45:26

标签: python multithreading

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

1 个答案:

答案 0 :(得分:4)

stop_thread()中,您的赋值语句会创建一个名为cont_running的局部变量。此局部变量与同名的全局变量无关。

试试这个:

def stop_thread():
    global cont_running
    cont_running = False