from threading import Thread
from threading import Event
import time
class ChildThread(Thread):
myStopSignal = 0
def __init__(self, aStopSignal):
Thread.__init__(self)
self.myStopSignal = aStopSignal
def run(self):
print("Child Thread:Started")
for i in range(1, 10):
if (self.myStopSignal.wait(0)):
print("ChildThread:Asked to stop")
break;
print("Doing some low priority task taking long time")
time.sleep(2) # Just simulating time taken by task with sleep
print("Child Thread:Exiting")
print("Main Thread:Started")
aStopSignal = Event()
aChildThread = ChildThread(aStopSignal)
aChildThread.start()
aChildThread.join(8) # I can wait for 4 seconds only
if aChildThread.is_alive() is True:
aStopSignal.set()
aChildThread.join()
print("Main Thread; Exiting")
import threading
import time
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s:%(message)s')
logger = logging.getLogger(__name__)
logger.info('infor')
logger.error('errof')
logging.warning('warning')
# make thread exit nicely
class MyThread9(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
global event
while True:
if event.isSet():
logging.warning(self.getName() + " is Running")
time.sleep(2)
else:
logging.warning(self.getName() + " stopped")
break;
event = threading.Event()
event.set()
def Test9():
t1 = []
for i in range(6):
t1.append(MyThread9())
for i in t1:
i.start()
time.sleep(10)
q = input("Please input exit:")
if q == "q":
event.clear()
if __name__ == '__main__':
Test9()