First we'll implement our TicketSeller class. This class will contain it's own internal counter for how many tickets that it has sold. In our constructor, we initialize our thread and take in the reference of the semaphore. Within our run function, we try to acquire this semaphore if the number of tickets we have available for sale is less than or equal to 0; if it is greater than 0, then we increment the number of tickets our ticketSeller has sold, and decrease ticketsAvailable by 1. We then release the semaphore and print out our progress.
class TicketSeller(threading.Thread):
ticketsSold = 0
def __init__(self, semaphore):
threading.Thread.__init__(self)
self.sem = semaphore
print("Ticket Seller Started Work")
def run(self):
global ticketsAvailable
running = True
while running:
self.randomDelay()
self.sem.acquire()
if(ticketsAvailable <= 0):
running = False
else:
self.ticketsSold = self.ticketsSold + 1
ticketsAvailable = ticketsAvailable - 1
print("{} Sold One ({} left)".format(self.getName(), ticketsAvailable))
self.sem.release()
print("Ticket Seller {} Sold {} tickets in total".format(self.getName(), self.ticketsSold))
def randomDelay(self):
time.sleep(random.randint(0,1))
In the preceding code, we define our TicketSeller class. This class features a constructor which takes in the reference of our global semaphore object, and also initializes our thread. Within our run function, we define a while loop that simulates blocking for anywhere between 0 and 1 seconds, and then tries to acquire the semaphore. Upon successful acquisition of the semaphore, it then checks to see if any tickets are available to sell. If there are, then it increments the number of ticketsSold and decrements ticketsAvailable before printing it's accomplishment out to the console.
Now that we've defined our TicketSeller class, we need to first create our semaphore object which will be passed to all instances of TicketSerllers, as follows:
# our sempahore primitive
semaphore = threading.Semaphore()
# Our Ticket Allocation
ticketsAvailable = 10
# our array of sellers
sellers = []
for i in range(4):
seller = TicketSeller(semaphore)
seller.start()
sellers.append(seller)
# joining all our sellers
for seller in sellers:
seller.join()