__author__ = "Narendra Boyina"
# -----------------------------------------------------------------------------
# Copyright (c) 2025 BR Technologies PVT LTD
# -----------------------------------------------------------------------------
"""
Topics to be covered in today's class:
--> How to import thread module with examples
"""
"""
Threading in python is used to run multiple threads (tasks/ function calls) at the same time.
Note that this does not mean that they are executed on different CPUs.
"""
from time import time, sleep
# import time
def sqaure(list):
for number in list:
# time.sleep(0.2) # hold the execution for 2 milli seconds
sleep(0.2) # hold the execution for 2 milli seconds
print("sqare of {0} is {1}".format(number, number**2))
def cube(list):
for number in list:
# time.sleep(0.2) # hold the execution for 2 milli seconds
sleep(0.2) # hold the execution for 2 milli seconds
print("Cube of {0} is {1}".format(number, number*number*number))
# print("Cube of {0} is {1}".format(number, number**3))
#
# start_time = time() # takes the current system time
# print(start_time)
# list = [1, 2, 3, 4]
# sqaure(list)
# cube(list)
# print(time()-start_time) # aproximately 1.62
"""
Output:
1539772873.8303847
sqare of 1 is 1
sqare of 2 is 4
sqare of 3 is 9
sqare of 4 is 16
Cube of 1 is 1
Cube of 2 is 8
Cube of 3 is 27
Cube of 4 is 64
1539772875.4356406
1.6052558422088623
"""
from threading import Thread
def sqaure(list):
for number in list:
sleep(0.2) # hold the execution for 2 milli seconds
print("sqare of {0} is {1}".format(number, number**2))
def cube(list):
for number in list:
# time.sleep(.2)
sleep(0.2) # hold the execution for 2 milli seconds
print("Cube of {0} is {1}".format(number, number**3))
input_1 = [1, 2, 3, 4]
input_2 = (2,3,4, 5)
starting_time = time() # takes the current system time
T1 = Thread(target=sqaure, args=(input_1,))
T2 = Thread(target=cube, args=(input_2,))
T1.start() # Start the thread's activity. Must be called at most once per thread object
T2.start()
T1.join() # to ensure that the main program waits for both threads to finish before continuing.
T2.join() # to ensure that the main program waits for both threads to finish before continuing.
print(time()-starting_time) # ending time - starting time # 0.80 seconds
"""
# Output:
======
sqare of 1 is 1
Cube of 1 is 1
sqare of 2 is 4
Cube of 2 is 8
sqare of 3 is 9
Cube of 3 is 27
sqare of 4 is 16
Cube of 4 is 64
0.8262016773223877
"""Author: Boyina Narendra
Supporting Author: M. Meera Sindhu
Request: If you find this information useful, please provide your valuable comments
No comments:
Post a Comment