perencia
perencia

Reputation: 1542

Why the thread does not stops?

The thread started in the start_thread method does not stop. Why ?

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

Upvotes: 1

Views: 33

Answers (1)

Robᵩ
Robᵩ

Reputation: 168626

In stop_thread(), your assignment statement creates a local variable named cont_running. This local variable is unrelated to the global variable of the same name.

Try this:

def stop_thread():
    global cont_running
    cont_running = False

Upvotes: 4

Related Questions