[Python] Synchronization and threading examples

[Python] Synchronization and threading examples

I want to present my code in Python solving Senate Bus Problem from The Little book of Semaphores (page 211). I’ve used several synchronizing objects such as Lock, Thread, Condition and Semaphore.
Here is link to Python threading library.

#!/usr/bin/env python
# Wojciech Jamrozy
# Script written during Operating Systems course VI 2009
# Problem: The Senate Bus Problem
from time import sleep
from threading import Lock, Thread, Condition, Semaphore
from random import random
import sys
waiting_passengers = 0
mutex = Lock()
bus = Condition()
on_board = Semaphore(0)
 
class Configuration:
        NUMBER_OF_BUSES = 15
        NUMBER_OF_PASSENGERS = 100
        BUS_DELAY = 5
        PASSENGER_DELAY = .8
        TIME_OF_BOARDING = 1
        SEATS = 10
 
 
class Bus(Thread):
    def __init__(self, numer):
        Thread.__init__(self)
        self.numer = numer
    def run(self):
        mutex.acquire()
        print "Bus %d arrived" % (self.numer,)
        global waiting_passengers
        n = min(waiting_passengers, Configuration.SEATS)
        for i in range(n):
            bus.acquire()
            bus.notify()
            bus.release()
            on_board.acquire()
            waiting_passengers -= 1
        sleep(Configuration.TIME_OF_BOARDING*random())
        print "Bus %d departed" % (self.numer,)
        mutex.release()
 
 
 
 
class Passenger(Thread):
    def __init__(self, numer):
        Thread.__init__(self)
        self.numer = numer
    def run(self):
        global waiting_passengers
        print "Passenger %d has come" % (self.numer,)
        mutex.acquire()
        waiting_passengers += 1
        mutex.release()
        bus.acquire()
        bus.wait()
        print "Passenger %d is on board" % (self.numer,)
        bus.release()
        on_board.release()
 
 
class CreateBuses(Thread):
    def run(self):
        for i in range(Configuration.NUMBER_OF_BUSES):
            b = Bus(i)
            b.start()
            sleep(random()*Configuration.BUS_DELAY)
        print "Creating buses finished - nacisnij ENTER aby zakonczyc"
 
class CreatePassengers(Thread):
    def run(self):
        for i in range(Configuration.NUMBER_OF_PASSENGERS):
            o = Passenger(i)
            o.start()
            sleep(random()*Configuration.PASSENGER_DELAY)
        print "Creating passengers finished - press ENTER in order to finish"
 
busy = CreateBuses()
passengers = CreatePassengers()
 
busy.start()
passengers.start()
 
raw_input("Press any key in order to finish\n") 
sys.exit()

Leave a Reply

Your email address will not be published.