2017-05-03 81 views
1

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

回答

4

stop_thread(),你的賦值語句創建一個名爲cont_running一個局部變量。這個局部變量與同名的全局變量無關。

試試這個:

def stop_thread(): 
    global cont_running 
    cont_running = False