Code Feedback

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • mwt

    #1

    Code Feedback

    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.Condi tion()

    def checkOutBook(se lf):
    #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.app end(nameOfBook)
    self.cv.notify( )
    self.cv.release ()


    class Reader(threadin g.Thread):

    def __init__(self, library, name, readingSpeed, timeBetweenBook s):
    threading.Threa d.__init__(self )
    self.library = library
    self.name = name
    self.readingSpe ed = readingSpeed
    self.timeBetwee nBooks = timeBetweenBook s
    self.bookName = ""


    def run(self):
    while 1:
    self.bookName = self.library.ch eckOutBook()
    print self.name, "reading", self.bookName
    time.sleep(self .readingSpeed)
    print self.name, "done reading", self.bookName
    self.library.re turnBook(self.b ookName)
    self.bookName = ""
    time.sleep(self .timeBetweenBoo ks)


    if __name__=="__ma in__":

    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

  • Dan M

    #2
    Re: Code Feedback

    > 2) Anybody know how to alter the "while 1: pass" section to make the[color=blue]
    > app stoppable?[/color]

    That one I think I can help with! See below.
    [color=blue]
    > while 1: pass[/color]

    try:
    while 1:
    pass
    except KeyboardInterru pt:
    break


    Comment

    • Peter Hansen

      #3
      Re: Code Feedback

      Dan M wrote:[color=blue][color=green]
      >>2) Anybody know how to alter the "while 1: pass" section to make the
      >>app stoppable?[/color]
      >
      >
      > That one I think I can help with! See below.
      >
      >[color=green]
      >> while 1: pass[/color]
      >
      >
      > try:
      > while 1:
      > pass
      > except KeyboardInterru pt:
      > break[/color]

      That might make it "stoppable" (or at least more cleanly stoppable than
      it is now) but it doesn't make it efficient.

      Adding something like "time.sleep(0.1 )" in place of "pass" is
      advisable... or the main thread will be "busy-waiting", using up CPU
      time, while waiting for Ctrl-C...

      -Peter

      Comment

      • Jorgen Grahn

        #4
        Re: Code Feedback

        On 6 Feb 2006 09:33:58 -0800, mwt <michaeltaft@gm ail.com> wrote:[color=blue]
        > 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[/color]
        ....[color=blue]
        > 1) Is this good Python code?[/color]

        Can't say, but it makes a pretty good reading list[0].
        [color=blue]
        > self.stacks = ["Heart of Darkness", "Die Verwandlung", "Lord of
        > the Flies", "For Whom the Bell Tolls", "Dubliners" , "Cyrano de
        > Bergerac"][/color]

        You might want to look into using doc strings properly. You have comments at
        the start of functions, but they read more like implementation notes than
        "what this method does and why". But I only had a quick look.

        /Jorgen
        [0] Note to self: pick up some Joseph Conrad later this week.

        --
        // Jorgen Grahn <grahn@ Ph'nglui mglw'nafh Cthulhu
        \X/ snipabacken.dyn dns.org> R'lyeh wgah'nagl fhtagn!

        Comment

        • snoe

          #5
          Re: Code Feedback

          I believe the while 1: pass is there to keep the main thread alive
          until all the readers are done. If you want the program to end after
          the readers are done you can append them all to a list then iterate
          through and wait for the threads to join()

          if __name__=="__ma in__":

          library = Library()
          readers = input("Number of Readers?")
          readerlist = []
          for i in range(1,readers ):
          newReader = Reader(library, "Reader" + str (i),
          random.randint( 1,7), random.randint( 1,7))
          newReader.start ()
          readerlist.appe nd(newReader)
          for reader in readerlist:
          reader.join()

          Comment

          • mwt

            #6
            Re: Code Feedback

            Thanks for all the feedback.
            Interestingly, I can't seem to get Dan M's code:
            Code:
            try:
            while 1:
            pass
            except KeyboardInterrupt:
            break
            to work, no matter how many variations I try (including adding in
            "time.sleep(0.1 )" as Peter Hansen suggested. The program just continues
            to execute, ignoring the command to stop. I'm guessing that this has
            something to do with the fact that the Reader threads are still
            running?

            A further question: Can anyone point me to a good description of the
            best way to write/use doc strings in Python?

            Comment

            • mwt

              #7
              Re: Code Feedback


              Jorgen Grahn wrote:[color=blue]
              > You might want to look into using doc strings properly. You have comments at
              > the start of functions, but they read more like implementation notes than
              > "what this method does and why". But I only had a quick look.[/color]

              Yeah. They were just my scaffolding notes to myself.

              I'd hurry up with that Conrad if I were you, and get on with the
              Hemingway. ;)

              Comment

              • Sion Arrowsmith

                #8
                Re: Code Feedback

                mwt <michaeltaft@gm ail.com> wrote:[color=blue]
                >1) Is this good Python code? What should be changed to make it more
                >Pythonesque?[/color]
                [color=blue]
                > while not len(self.stacks ) > 0:[/color]

                while not self.stacks:

                An empty list is considered to be false, hence testing the list
                itself is the same as testing len(l) > 0 .

                --
                \S -- siona@chiark.gr eenend.org.uk -- http://www.chaos.org.uk/~sion/
                ___ | "Frankly I have no feelings towards penguins one way or the other"
                \X/ | -- Arthur C. Clarke
                her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump

                Comment

                Working...