Threading question

T

Torsten Marek

Hello to all,

I have a simple question about threads in Python. I am starting a
number of threads in my program and I want print out the amount of time
needed after all threads stopped. Do I need to explictly join the
threads, set a condition or is it possible to somehow work with
try/finally like that:

try:
for i in range(0, num_threads):
s = MyThread()
s.start()
finally:
print "all threads finished"


Thanks in advance

Torsten
 
P

Peter Hansen

Torsten said:
I have a simple question about threads in Python. I am starting a
number of threads in my program and I want print out the amount of time
needed after all threads stopped. Do I need to explictly join the
threads, set a condition or is it possible to somehow work with
try/finally like that:

try:
for i in range(0, num_threads):
s = MyThread()
s.start()
finally:
print "all threads finished"

The other threads are running in, well, other threads, so you
won't see any effect on the above thread when they end. Therefore
you can't get much mileage out of a finally clause. A .join()
is definitely the way to go here.

-Peter
 
T

Torsten Marek

Peter said:
The other threads are running in, well, other threads, so you
won't see any effect on the above thread when they end. Therefore
you can't get much mileage out of a finally clause. A .join()
is definitely the way to go here.

-Peter
I found another way to go for now, which works fine for me.
Since the threading module sets sys.exitfunc, I just do:

def my_exitfunc():
global thread_wait
thread_wait()
# own stuff follows here...

thread_wait = sys.exitfunc
sys.exitfunc = my_exitfunc

That's maybe not very clean, but it's just a minor script I wrote, so I
don't want to waste to much time on it;-)

Anyway, thanks for the answer

Torsten
 
P

Peter Hansen

I found another way to go for now, which works fine for me.
Since the threading module sets sys.exitfunc, I just do:

def my_exitfunc():
global thread_wait
thread_wait()
# own stuff follows here...

thread_wait = sys.exitfunc
sys.exitfunc = my_exitfunc

That's maybe not very clean, but it's just a minor script I wrote, so I
don't want to waste to much time on it;-)

Good solution. You're actually taking advantage of the fact that
the main thread does a join() on all non-daemon threads automatically
as it exits. The source in threading.py for the "main thread"
can make illuminating reading...

-Peter
 

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

Forum statistics

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

Latest Threads

Top