Vidyavardhini’s College of Engineering & Technology
Department of Computer Engineering
xperiment No. 11
E
Demonstrate the concept of Multi-threading
Date of Performance:02/04/25
Date of Submission:09/04/25
Vidyavardhini’s College of Engineering & Technology
Department of Computer Engineering
Experiment No. 11
Title:Demonstrate the concept of Multi-threading
Aim:To study and implement the concept of Multi-threading
Objective:To introduce the concept of Multi-threadingin python
Theory:
Thread
I n computing, a processis an instance of a computerprogram that is being executed. Any
process has 3 basic components:
● An executable program.
● The associated data needed by the program (variables, work space, buffers, etc.)
● The execution context of the program (State of process)
A t hreadis an entity within a process that can bescheduled for execution. Also, it is the
smallest unit of processing that can be performed in an OS (Operating System).
I n simple words, a threadis a sequence of such instructionswithin a program that can be
executed independently of other code. For simplicity, you can assume that a thread is simply
a subset of a process!
A thread contains all this information in a ThreadControl Block (TCB):
● Thread Identifier:Unique id (TID) is assigned toevery new thread
● Stack pointer:Points to thread’s stack in the process.Stack contains the local variables
under thread’s scope.
● Program counter:a register which stores the addressof the instruction currently being
executed by thread.
● Thread state:can be running, ready, waiting, startor done.
● Thread’s register set:registers assigned to threadfor computations.
● Parent process Pointer:A pointer to the Process controlblock (PCB) of the process that
the thread lives on.
Vidyavardhini’s College of Engineering & Technology
Department of Computer Engineering
ode:
C
import threading
import os
import time
import concurrent.futures
def print_cube(num):
print("Cube: {}".format(num * num * num))
def print_square(num):
print("Square: {}".format(num * num))
if __name__ == "__main__":
t1 = threading.Thread(target=print_square, args=(10,))
t2 = threading.Thread(target=print_cube, args=(10,))
t1.start()
t2.start()
t1.join()
t2.join()
print("Done!")
def task1():
print("Task 1 assigned to thread: {}".format(threading.current_thread().name))
print("ID of process running task 1: {}".format(os.getpid()))
def task2():
print("Task 2 assigned to thread: {}".format(threading.current_thread().name))
print("ID of process running task 2: {}".format(os.getpid()))
if __name__ == "__main__":
print("ID of process running main program: {}".format(os.getpid()))
print("Main thread name: {}".format(threading.current_thread().name))
t1 = threading.Thread(target=task1, name='t1')
t2 = threading.Thread(target=task2, name='t2')
t1.start()
t2.start()
t1.join()
Vidyavardhini’s College of Engineering & Technology
Department of Computer Engineering
t2.join()
def worker():
print("Worker thread running")
ool = concurrent.futures.ThreadPoolExecutor(max_workers=2)
p
pool.submit(worker)
pool.submit(worker)
pool.shutdown(wait=True)
print("Main thread continuing to run")
x = 0
def increment():
global x
x += 1
def thread_task():
for _ in range(100000):
increment()
def main_task():
global x
x = 0
t1 = threading.Thread(target=thread_task)
t2 = threading.Thread(target=thread_task)
t1.start()
t2.start()
t1.join()
t2.join()
if __name__ == "__main__":
for i in range(10):
main_task()
Vidyavardhini’s College of Engineering & Technology
Department of Computer Engineering
print("Iteration {0}: x = {1}".format(i, x))
class DummyThread(threading.Thread):
def __init__(self, name, priority):
threading.Thread.__init__(self)
self.name = name
self.priority = priority
def run(self):
name = self.name
time.sleep(1.0 * self.priority)
print(f"{name} thread with priority {self.priority} is running")
t1 = DummyThread(name='Thread-1', priority=4)
t2 = DummyThread(name='Thread-2', priority=1)
t1.start()
t2.start()
t1.join()
t2.join()
print('All Threads are executed')
Conclusion:MultithreadinginPythonturnedouttobeprettyeffective.Byrunningmultiple
threads at the same time, the program wasabletomakebetteruseofsystemresourcesand
threadingmodulemadeiteasierto
handletasksmoreefficiently.UsingPython’sbuilt-in
managesynchronizationandavoidissueslikeraceconditionswhenmultiplethreadsaccessed
shared data. It worked well for both I/O-bound and CPU-heavy tasks, showing just how
Vidyavardhini’s College of Engineering & Technology
Department of Computer Engineering
flexibleandreliablePythoncanbewhenitcomestomultithreading.Overall,theexperiment
highlighted how practical and useful this approach is in real-world Python programming.