[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 -- http://mail.python.org/mailman/listinfo/python-list