Python code using threads
Steve Holden
sholden at bellatlantic.net
Mon Feb 28 00:10:02 EST 2000
Jason Stokes wrote:
>
> Can anyone point me in the direction of some good open source Python code
> that uses threading and locking? I learn best by reading production level
> code.
For locking, search deja news. There has been some recent discussion on
the topic. For threading I can do no better than repeat
jblaine at shell2.shore.net (Jeff Blaine)'s
recent post (once is never enough, especially for me):
Ripped straight from Aahz Maruch's post the other day and simplified
as more of a 'visual learning tool' demo. Added a few comments...
whatever...just posting in case someone finds this one more graspable
at a thread-beginner level like me.
#!/usr/local/bin/python
import time, threading, whrandom
class MyThread(threading.Thread):
""" Each thread picks a 'random' integer between 0 and 19 and reports
in once per second for that many seconds.
"""
def run(self):
iterations = whrandom.randint(0, 19)
for i in range(iterations):
print " ", self.getName(), "is reporting in"
time.sleep(1)
print self.getName(), "is DONE"
if __name__ == '__main__':
threadList = []
# Create 5 MyThread() threads
for i in range(5) :
thread = MyThread()
threadList.append(thread)
# Start all threads
for thread in threadList:
thread.start()
# As long as we have more than just the 'main' thread running, print out
# a status message
while threading.activeCount() > 1 :
print str(threading.activeCount()), "threads running including main"
time.sleep(1)
Please note, you should not expect this to run under Idle, which gave somewhat
incomprehensible results to a newbie like me, but it works fine as a
standalone.
regards
Steve
--
"If computing ever stops being fun, I'll stop doing it"
More information about the Python-list
mailing list