simple Thread question

David Pokorny davebrok at soda.csua.berkeley.edu
Tue Aug 17 13:29:43 EDT 2004


"adeger" <adeger at netlibrary.com> wrote in message
news:b8001e9f.0408041233.1b3ca73c at posting.google.com...
> JCM <josh at work.com> wrote in message
news:<ceosom$6ln$1 at fred.mathworks.com>...
> > You should override the run method, but call thread.start() to kick
> > the execution off in a separate thread.  If you call thread.run(),
> > you're just running your code in the same thread.
> >
>
> Thanks JCM and everyone else for your help!  This wasn't that clear to
> me reading the docs (I really DID read them) and your answer saved me
> a bunch of personal (and program execution) time!

It's worth pointing out that while print bytecodes are atomic, print
statements are not.
So unless a) you use your own lock to control output via "print"
or b) you pass only 1 argument to print, you run the risk of creating output
like:

...
thread  a  instance  33
thread  a  instance  34
thread  a  instance  35
thread  a  instance  36
thread  a  instance  37
thread  a  instance  38
thread  a thread  b  instance   instance  39
1
thread  thread  a  instance  b  instance  2
40
thread  a thread  b  instance  3
thread  b  instance  4
thread  b  instance  5
thread  b  instance  6
thread  b  instance  7
...


To create the desired bad behavior, comment out the three statements that
refer to plock.
---
import threading,time,sys

plock = threading.Lock()

class TestThr(threading.Thread):
    def __init__(self,name):
        self.name = name
        threading.Thread.__init__(self)

    def run(self):
        for i in range(1,100):
            plock.acquire()
            print 'thread', self.name, 'instance', str(i)
            plock.release()
            #time.sleep(.1)

def test():
    for tname in ('a', 'b', 'c'):
        thread = TestThr(tname)
        thread.start()

---
David





More information about the Python-list mailing list