herman wrote:
Hi,
In my python program, I would to like to spwan 5 threads, for the them
for 5 minutes maximum and the continue. Here is my script:
threads = []
for j in range(5):
t = MyThread()
threads.append(t)
for t in threads:
t.join(60*5)
print "thread join\n"
# wait for 5 minutes for all the threads to complete ,
and
# then continue
But this code ends up waiting 5 minutes for **each** thread. that is
not what I want. I just want to wait for 5 minutes for all threads.
how can I do that?
And after 5 minutes, i want to kill off all the threads I spawn
earlier, how can I do that in python.
Thank you for any help.
Well, to answer your second question, there is no reliable way to kill a
thread without having the thread periodically examine some aspect of
its environment that the main thread can change to indicate the
requirement that the sub-thread terminate.
The easiest way to check the number of outstanding threads is to use
threading.activeCount(), which tells you how many outstanding threads
remain.
Here's some code I used in a test program recently:
# As long as we have more than just the 'main' thread running,
# print out a status message
while threading.activeCount() 1 :
print "-- after", iterCount, "sleeps", \
str(threading.activeCount()), "threads running in total"
iterCount += 1
time.sleep(1)
print "Only main thread remains"
Clearly you will need to set some termination flag (a global variable
would do) after time is up, and as long as your threads examine this
flag you'll be good to go.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd
http://www.holdenweb.com
Skype: holdenweb
http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------