473,394 Members | 1,714 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Code Feedback

mwt
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

Feb 6 '06 #1
7 1244
> 2) Anybody know how to alter the "while 1: pass" section to make the
app stoppable?
That one I think I can help with! See below.
while 1: pass


try:
while 1:
pass
except KeyboardInterrupt:
break
Feb 6 '06 #2
Dan M wrote:
2) Anybody know how to alter the "while 1: pass" section to make the
app stoppable?

That one I think I can help with! See below.

while 1: pass

try:
while 1:
pass
except KeyboardInterrupt:
break


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

Feb 6 '06 #3
On 6 Feb 2006 09:33:58 -0800, mwt <mi*********@gmail.com> wrote:
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 .... 1) Is this good Python code?
Can't say, but it makes a pretty good reading list[0].
self.stacks = ["Heart of Darkness", "Die Verwandlung", "Lord of
the Flies", "For Whom the Bell Tolls", "Dubliners", "Cyrano de
Bergerac"]


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.dyndns.org> R'lyeh wgah'nagl fhtagn!
Feb 6 '06 #4
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__=="__main__":

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.append(newReader)
for reader in readerlist:
reader.join()

Feb 6 '06 #5
mwt
Thanks for all the feedback.
Interestingly, I can't seem to get Dan M's code:
Expand|Select|Wrap|Line Numbers
  1. try:
  2. while 1:
  3. pass
  4. except KeyboardInterrupt:
  5. break
  6.  
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?

Feb 7 '06 #6
mwt

Jorgen Grahn wrote:
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.


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. ;)

Feb 7 '06 #7
mwt <mi*********@gmail.com> wrote:
1) Is this good Python code? What should be changed to make it more
Pythonesque? while not len(self.stacks) > 0:


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 -- si***@chiark.greenend.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
Feb 7 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Dafella | last post by:
The following is code from Xeoport. It is suppose to access my pop3 account and load email into Mysql database. It's not inserting and there is no log or anything to tell me why. Here is the...
26
by: Michael Strorm | last post by:
Hi! I posted a message a while back asking for project suggestions, and decided to go with the idea of creating an adventure game (although it was never intended to be a 'proper' game, rather an...
2
by: Sergio del Amo | last post by:
Hi, I wrote some functionality for a Web Page with Javascript. My code works perfectly for Firefox but not for IE. I become some errors apparently all based in the same problem wich scapes to my...
2
by: Kavitha Rao | last post by:
Hi, I am getting the following errors while trying to run this snippet in Microsoft Visual C++.Can't seem to print the crc value stored. /* +++Date last modified: 05-Jul-1997 */ /* Crc - 32...
192
by: Vortex Soft | last post by:
http://www.junglecreatures.com/ Try it and tell me what's happenning in the Microsoft Corporation. Notes: VB, C# are CLS compliant
1
by: Terry Olsen | last post by:
No offense to anyone in this group, particularly Tom Shelton, Michael M, or Newbie Coder. But who the hell is Crouchie1998 and why is he accusing every submission I make to Planet Source Code to be...
2
by: DrNoose | last post by:
Hi! I'm working on code for a feedback form. I want the data from the user that is taken from the form to be emailed back to me. I'm using vb with visual studios 2005. I have most of the...
9
by: gs | last post by:
the feedback for the install of c#2008 places 97 to 99% cpu load for way too long on athlon x64 3800+ PC. 3/4 an hour later its only about 80% complete, continuing with 98% CPU load! Next time...
27
by: George2 | last post by:
Hello everyone, Should I delete memory pointed by pointer a if there is bad_alloc when allocating memory in memory pointed by pointer b? I am not sure whether there will be memory leak if I do...
8
by: Brian | last post by:
What's the best way to debug code that is being run during garbage collection? We are getting AccessViolationExceptions that seem to be happening during garbage collection. But when it hits the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.