Problem Statement:
Demonstrate the usage of threading in python.

Let’s consider an example where we have two scripts, one of them is the “” script that can be considered as parent and the other that would run in threads “”.

Let’s first take a look at
import time

class log:
def __init__(self, times):
self.times = times
self._bOn = True

def start(self):
while (self._bOn):
print “in start”

def stop(self):
self._bOn = False
print “in stop” contains a class log with constructor that takes argument for time and sets the bOn variable to True.
start() – starts printing “in start” till the time bOn is True.
stop() – prints “in stop” when it is called. It would also stop the start() function as bOn is set to False now.

Now on to the parent script that would call to run in thread.
import os
import log
import time
import thread

obj = log.log(5)

def startlog():
print “in thread”

obj.stop(), imports with constructor argument as “5”.
startlog() – prints “in thread” and then would call start() of
startlog() is now run as a thread
Main script sleeps for 11 seconds and then
calls the stop() of

In this example, when starts running, it imports and sets the argument(time) of the constructor to 5. It then starts a thread for the function startlog() and goes to sleep for 11 seconds.
Now that a thread has started with startlog() function, it prints “in thread”, then calls start() of Now that bOn is True, it prints “in start” and sleeps for 5 seconds as set by After 5 seonds again it prints “in start”.
During this time the is still sleeping. When 11 seconds pass by, comes out of sleep ( is still running though) and calls the stop() of Because of which, start() gets stopped as bOn is now set to False and it prints “in stop”.
Thus we have seen, and both ran in parallel and could control the execution of as it was run in thread.