Question: Objective: Implement a program that uses multiple threads Instructions: A theater has a total of 1 0 0 seats. People are trying to book tickets
Objective:
Implement a program that uses multiple threads
Instructions:
A theater has a total of seats. People are trying to book tickets simultaneously from different counters threads
Each thread will attempt to book a ticket for a person.
Your task is to simulate the ticket booking process using threads, ensuring that no two threads can book the same seat at the same time ie avoiding race conditions
You will implement the following:
Booking Counter Thread: Each thread represents a booking counter, where a person tries to book a ticket.
Synchronization: Use locks to ensure that each seat is booked by only one person.
Shared Data: The total number of seats is shared among the threads, and this shared data should be accessed in a threadsafe way.
Result: Print the seat number each person booked. If no seats are available, print that the booking failed.
Tasks:
Step : marks
Import Required Modules You need to import the necessary modules for multithreading. Use the threading module to create threads and time for simulating delays.
Step marks:
Define a TicketBooking Class Create a TicketBooking class to represent the ticket booking system. This class will have:
A shared variable for the number of available seats selfavailableseatsA Lock object to control access to the shared data.A method bookseatself counterid that each thread will call to attempt booking a seat.
Step : marks
Implement the bookseat Method The bookseat method should:
Acquire the lock to ensure threadsafe access to shared data.Check if there are any available seats left.If seats are available, decrement the seat count and print the seat number.Release the lock after updating shared data.
Step : marks
Create and Start Threads Write a function to create multiple threads representing booking counters and start them. Each thread should call the bookseat method.
Step : marks
Wait for Threads to Complete Ensure that the main program waits for all threads to finish before exiting.
Example Output:
Counter booked seat
Counter booked seat
Counter booked seat
Counter booked seat
Counter booked seat
No seats available for Counter
No seats available for Counter
Use the attached py file as your starter code. Complete the code as outlined above.
class TicketBooking:
pass
def main:
# define max seats
# instantiate ticket booking instance
# create a list to hold all the threads
threads
# Create threads simulating counters
# Wait for all threads to finish
if namemain:
main
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
