Friday 18 December 2015

Python: Terminate thread using global variable

In this post, I am going to explain how to terminate a thread using global variable.

test.py
import threading
import time

class MyThread(threading.Thread):
 def run(self):
  i=0
  while(not dead):
   i+=1
  print("Value of i is " , i)
 
 
global dead
dead = False
thread1 = MyThread(name="Thread_1")
thread1.start()

time.sleep(2)
dead = True

Above program terminate thread after 2 seconds. Program defines global variable dead, and terminates thread whenever dead is set to True.

Sample Outputs
$ python3 MyThread.py 
Value of i is  29546082
$
$ python3 MyThread.py 
Value of i is  26691508



Previous                                                 Next                                                 Home

No comments:

Post a Comment