Python multi threading:
stoppable thread:
many of you heard about threading in python is very bad.
its not easy to stop it but there are several method to do that thing happen .
so lets get started.
create file name called <filename>.py then paste this code in your text editor.
import threading
import time
##writer = Robokishan
##stopable thread
class ThreadingExample(object):
""" Threading example class
The run() method will be started and it will run in the background
until the application exits.
"""
#NOTE: STOPING THREAD IS BAD METHOD
def __init__(self, interval=1):
""" Constructor
:type interval: int
:param interval: Check interval, in seconds
"""
self.interval = interval
thread = threading.Thread(target=self.run, args=())
self._stop = threading.Event()
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def stop(self):
#function for stoping thread
print "thread stopped"
self._stop.set()
def stopped(self):
#function for check if thread is stopped or not
return self._stop.isSet()
def run(self):
""" Method that runs forever """
while True:
# Do something
print('Doing something imporant in the background')
time.sleep(self.interval)
print self.stopped()
example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
example.stop()
print example.stopped()
import time
##writer = Robokishan
##stopable thread
class ThreadingExample(object):
""" Threading example class
The run() method will be started and it will run in the background
until the application exits.
"""
#NOTE: STOPING THREAD IS BAD METHOD
def __init__(self, interval=1):
""" Constructor
:type interval: int
:param interval: Check interval, in seconds
"""
self.interval = interval
thread = threading.Thread(target=self.run, args=())
self._stop = threading.Event()
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def stop(self):
#function for stoping thread
print "thread stopped"
self._stop.set()
def stopped(self):
#function for check if thread is stopped or not
return self._stop.isSet()
def run(self):
""" Method that runs forever """
while True:
# Do something
print('Doing something imporant in the background')
time.sleep(self.interval)
print self.stopped()
example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
example.stop()
print example.stopped()
#######################
Dont just copy and paste the code because there are some indent
problem occured due to web view so please type and learn if you wanted to learn how this is work let me know in the comment section.
please subscribe to my YouTube channel :
Comments
Post a Comment