Hello - Last night I wrote my first code in Python -- a little producer/consumer toy to help me begin to understand things. The "Library" only has a few books. You can choose how many Readers are trying to check out the books. When no books are available, they have to wait until some other Reader returns one. Readers are assigned random reading speeds and wait times between
It runs fine, but I have a few questions about it. 1) Is this good Python code? What should be changed to make it more Pythonesque? 2) Anybody know how to alter the "while 1: pass" section to make the app stoppable? 3) The synchronization I'm using works, but is there a better way to do it? Thanks for any insight/pointers, etc. Also, for any newbies like me, feel free to post variations of this code. In the next version, I'm going to make it so that readers can't check out the same book twice. Here's the code: #!/usr/bin/python # Filename: Library.py # author: MWT # 5 Feb, 2006 import thread import time import threading import random class Library: #The goal here is to create a synchronized list of books def __init__(self): self.stacks = ["Heart of Darkness", "Die Verwandlung", "Lord of the Flies", "For Whom the Bell Tolls", "Dubliners", "Cyrano de Bergerac"] self.cv = threading.Condition() def checkOutBook(self): #remove book from the front of the list, block if no books are available self.cv.acquire() while not len(self.stacks) > 0: self.cv.wait() print "waiting for a book..." bookName = self.stacks.pop(0) self.cv.release() return bookName def returnBook(self, nameOfBook): #put book at the end of the list, notify that a book is available self.cv.acquire() self.stacks.append(nameOfBook) self.cv.notify() self.cv.release() class Reader(threading.Thread): def __init__(self, library, name, readingSpeed, timeBetweenBooks): threading.Thread.__init__(self) self.library = library self.name = name self.readingSpeed = readingSpeed self.timeBetweenBooks = timeBetweenBooks self.bookName = "" def run(self): while 1: self.bookName = self.library.checkOutBook() print self.name, "reading", self.bookName time.sleep(self.readingSpeed) print self.name, "done reading", self.bookName self.library.returnBook(self.bookName) self.bookName = "" time.sleep(self.timeBetweenBooks) if __name__=="__main__": library = Library() readers = input("Number of Readers?") for i in range(1,readers): newReader = Reader(library, "Reader" + str (i), random.randint(1,7), random.randint(1,7)) newReader.start() while 1: pass -- http://mail.python.org/mailman/listinfo/python-list