Threading Problem

Steve Holden steve at holdenweb.com
Wed Dec 22 13:41:31 CET 2004


Norbert wrote:

> Hello *,
> 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())
> th.start()
> print "start completed"
> #--------------------
> (the dots are inserted becaus Google mangles the lines otherwise)
> 
> This program gives the following result :
> ----
> start
> threadfunction: entered
> threadfunction x=10
> threadfunction x=20
> threadfunction x=30
> start completed
> ----
> My aim was that the main program should continue to run while
> threadfunction runs in parallel. That's the point of threads after all,
> isn't it ?
> 
> I awaited something like the following :
> start
> threadfunction: entered
> start completed                <-------------------
> threadfunction x=10
> threadfunction x=20
> threadfunction x=30
> 
> Does anyone know what's going on here ?
> 

Well, I don't believe there's any guarantee that a thread will get run 
preference over its starter - they're both threads, after all. Try 
putting a sleep after th.start() and before the print statement and you 
should see that the "worker" thread runs while the main thread sleeps.

The same would be true if each were making OS calls and so on. When 
everything is more or les continuous computation, and so short it can be 
over in microseconds, there's no motivation for the scheduler to stop 
one thread and start another.

regards
  Steve
-- 
Steve Holden               http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC      +1 703 861 4237  +1 800 494 3119



More information about the Python-list mailing list