<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">#At this problem we have 4 study rooms and 24 students.
#All the students (threads) want to enter a study room
#in order to study, but each study room can accommodate
#at most 4 students. Also, each student who enters a
#study room should write her/his name on the wall and then
#leave. Use semaphores to implement the capacity constraints
#and the atomic write on the wall. If there is empty space
#in a study room, it should be immediately occupied by a waiting student.
#Which means that the students should not be blocked waiting
#outside a specific study room. They should search the rooms
#until they find a vacancy.


from threading import Thread, Lock, Semaphore
import time
import random

def random_sleep():
    sleep_time = random.randint(1, 10000)
    time.sleep(sleep_time/100000.0)

class Student(Thread):

    def __init__(self, myid):
        self.myid = myid
        Thread.__init__(self)

    def run(self):
        times = 0
        #Each student should enter a study room 2 times.
        #The student searches all the study rooms to find
        #a vacant space.
        while times &lt; 2:
            random_sleep()
            times += studyroom1.enter(self.myid)
            random_sleep()
            if(times &lt;2):
                times += studyroom2.enter(self.myid)
            random_sleep()
            if(times &lt;2):
                times += studyroom3.enter(self.myid)
            random_sleep()
            if(times &lt;2):
                times += studyroom4.enter(self.myid)

class StudyRoom:
    def __init__(self):
        self.wall = ''
        #Initialize semaphores and/or other variables, like counters.

    
    def enter(self, myid):
        #enter if you can
            #study
            random_sleep()
            #write on the wall
            self.wall += ' ' + str(myid)
            #add an assert to be sure about the capacity
            #return 1 if you entered the study room.
        #return 0 if you did not enter the study room.

    def printwall(self):
        print self.wall
        

studyroom1 = StudyRoom()
studyroom2 = StudyRoom()
studyroom3 = StudyRoom()
studyroom4 = StudyRoom()

s = []	
		
for i in range(24):
    s[len(s):] = [Student(i)]

for i in range(24):
    s[i].start()

for i in range(24):
    s[i].join()

studyroom1.printwall()
studyroom2.printwall()
studyroom3.printwall()
studyroom4.printwall()

# vim:expandtab:tabstop=8:shiftwidth=4:softtabstop=4
</pre></body></html>