Experiment No.
11
Demonstrate the concept of Multi-threading
Date of Performance: 09/04/2025
Date of Submission: 16/04/2025
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-threading in python
Theory:
Thread
In computing, a process is an instance of a computer program 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 thread is an entity within a process that can be scheduled for execution. Also, it is the
smallest unit of processing that can be performed in an OS (Operating System).
In simple words, a thread is a sequence of such instructions within 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 Thread Control Block (TCB):
● Thread Identifier: Unique id (TID) is assigned to every 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 address of the instruction currently being
executed by thread.
● Thread state: can be running, ready, waiting, start or done.
● Thread’s register set: registers assigned to thread for computations.
● Parent process Pointer: A pointer to the Process control block (PCB) of the process that
the thread lives on.
Code :
import threading import time
class TicketBookingSystem: def init(self, total_tickets): self.total_tickets = total_tickets #
Total available tickets self.lock = threading.Lock() # Lock for synchronization
def book_ticket(self, user_id):
"""Method to book a ticket by a user"""
with self.lock: # Ensures only one thread modifies ticket count at a time
if self.total_tickets > 0:
print(f"User {user_id} is booking a ticket...")
time.sleep(1) # Simulating delay in booking process
self.total_tickets -= 1
print(f"User {user_id} successfully booked a ticket! Remaining tickets:
{self.total_tickets}")
else:
print(f"User {user_id} tried to book, but no tickets left!")
Total available tickets
total_tickets = 5 booking_system = TicketBookingSystem(total_tickets)
Number of users (threads) trying to book tickets
num_users = 10 threads = []
for user_id in range(1, num_users + 1):
thread = threading.Thread(target=booking_system.book_ticket, args=(user_id,))
threads.append(thread) thread.start()
Wait for all threads to complete
for thread in threads: thread.join()
print("All users have attempted booking.")
Output :
User 1 is booking a ticket...
User 1 successfully booked a ticket! Remaining tickets: 4
User 2 is booking a ticket...
User 2 successfully booked a ticket! Remaining tickets: 3
User 3 is booking a ticket...
User 3 successfully booked a ticket! Remaining tickets: 2
User 4 is booking a ticket...
User 4 successfully booked a ticket! Remaining tickets: 1
User 5 is booking a ticket...
User 5 successfully booked a ticket! Remaining tickets: 0
User 6 tried to book, but no tickets left!
User 7 tried to book, but no tickets left!
User 8 tried to book, but no tickets left!
User 9 tried to book, but no tickets left!
User 10 tried to book, but no tickets left!
All users have attempted booking.
Conclusion:
Multithreading has been effectively implemented in Python, enabling concurrent execution of
multiple threads within a program. This implementation enhances resource utilization and
optimizes task efficiency. The use of Python's threading module ensures synchronization and
prevents race conditions during shared resource access. Both I/O-bound and computational
tasks were handled seamlessly, demonstrating Python's robustness in multithreading. Overall,
this experiment showcases the practicality and versatility of multithreading in Python
programming.