Threading Problem

Ishwor ishwor.gurung at gmail.com
Wed Dec 22 11:13:55 EST 2004


On Wed, 22 Dec 2004 12:55:46 +0000, Alan Kennedy <alanmk at hotmail.com> wrote:
> [Norbert]
> > i am experimenting with threads and get puzzling results.
> > Consider the following example:
> > #--------------------
> > import threading, time
> >
> > def threadfunction():
> > ....print "threadfunction: entered"
> > ....x = 10
> > ....while x < 40:
> > ........time.sleep(1) # time unit is seconds
> > ........print "threadfunction x=%d" % x
> > ........x += 10
> >
> >
> >
> > print "start"
> > th = threading.Thread(target = threadfunction())
> 
> The problem is here                            ^^
> 
> You are *invoking* threadfunction, and passing its return value as the
> target, rather than passing the function itself as the target. That's
> why threadfunction's output appears in the output stream before the
> thread has even started.
> 
> Try this instead
> 
> #-----------------------------------------------
> 
> import threading, time
> 
> def threadfunction():
>   print "threadfunction: entered"
>   x = 10
>   while x < 40:
>     time.sleep(1) # time unit is seconds
>     print "threadfunction x=%d" % x
>     x += 10
> 
> print "start"
> th = threading.Thread(target = threadfunction)
> th.start()
> print "start completed"
> 
> #------------------------------------------------
> 
> Which should output the expected
> 
> >
> start
> threadfunction: entered
> start completed
> threadfunction x=10
> threadfunction x=20
> threadfunction x=30
> 
> regards,
> 
> --
> alan kennedy
> ------------------------------------------------------
> email alan:              http://xhaus.com/contact/alan

nice chum ;) liked the way you explained. Clear and easy to
understand.. why doesn't the keyboardInterrupt seem to work? I am
working in IDLE and it doesn't seem to stop the thread ???!!??
output of above code in IDLE shell:----

threadfunction x=75

KeyboardInterrupt
>>> 
threadfunction x=80



-- 
cheers,
Ishwor Gurung



More information about the Python-list mailing list