Noob can't make threads work

S

Steve Horsley

I am trying to start two threads to do some time consuming work. This is my
first stab at threading, and it isn't working as I expect. Instead of the
threads starting when I call start(), they seem to run the target code as
part of the constructor call.

Here is my test code...

#!/usr/bin/python

import time
import threading

def fiddle():
for n in range(3):
print n
time.sleep(1)

print 'Creating threads...'
t1 = threading.Thread(target=fiddle())
t2 = threading.Thread(target=fiddle())
print 'Starting threads...'
t1.start()
t2.start()


I was expecting output like this:

Creating threads...
Starting threads...
0
0
1
1
2
2

but I get this instead:

Creating threads...
0
1
2
0
1
2
Starting threads...

This is in python 2.3 on Linux and also python 2.4 on XP.
Either threading in Python is badly broken, or I'm missing something
fundamental. I know which is most likely, but I can't figure it out.

Could someone point me in the right direction, plese?

TIA
Steve
 
G

Grant Edwards

I am trying to start two threads to do some time consuming work. This is my
first stab at threading, and it isn't working as I expect. Instead of the
threads starting when I call start(), they seem to run the target code as
part of the constructor call.

Here is my test code...

#!/usr/bin/python

import time
import threading

def fiddle():
for n in range(3):
print n
time.sleep(1)

print 'Creating threads...'
t1 = threading.Thread(target=fiddle())
t2 = threading.Thread(target=fiddle())

t1 = threading.Thread(target=fiddle)
t2 = threading.Thread(target=fiddle)
 
S

Steve Horsley

Grant said:
t1 = threading.Thread(target=fiddle)
t2 = threading.Thread(target=fiddle)


Doh! Slap that forehead!

Of course, I was calling fiddle() and using the
return value (None) as the target argument. And
a Thread with a target of None does nothing
when start()ed.

Many thanks.
Steve
 
G

Grant Edwards

Doh! Slap that forehead!

Of course, I was calling fiddle() and using the
return value (None) as the target argument. And
a Thread with a target of None does nothing
when start()ed.

Been there, done that.
 
S

Steve Holden

Grant said:
Been there, done that.
And, speaking of T-shirts, time for this week's reminder that PyCon is
now only three weeks away!

regards
Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top