sleep and Timer
Rob Hall
robhall at ii.net
Thu May 29 03:39:52 EDT 2003
> >def run(self):
> > while self.quit = false:
> > DO SOME STUFF
> > time.sleep(120)
> What if instead of sleeping you had an event object and waited for it with
a timeout of 120, e.g.,
> evt.wait(120)
> if evt.isSet(): # means another thread set the event, meaning
kill
> # die here -- should be immediately after event is set
> #otherwise just let loop continue around
> >
>
I rather like this approach. It works well.
The trouble is, once I go above 200 threads, it starts to bog down.
See my other post for an example using sleep(), together with some stats.
With the same problem here, using your solution, I get the following stats:
Time to create 500 threads: 216.85
Time to kill all threads: 34.72
As you can see, when working with a large number of threads, it isn't quite
upt-to-speed (excuse the pun).
But I love the solution for a small number of threads! In this case it is
comparible in speed. Thanks!
Here is the ammended program:
import time
import threading
import random
class test(threading.Thread):
def __init__(self, number):
threading.Thread.__init__(self)
self.terminate = 0
self.number = number
self.evt = threading.Event()
def run(self):
print 'Thread %d launched' % self.number
sleepTime = random.random() * 10
while 1:
self.evt.wait(sleepTime)
if self.evt.isSet():
break
print '>>>> Thread %d terminated.' % self.number
def quit(self):
print 'Exiting thread %d.' % self.number
self.evt.set()
# Create the threads
startCreate = time.time()
threadList = []
for number in range(1,501):
t = test(number)
t.start()
threadList.append(t)
endCreate = time.time()
time.sleep(2)
# Kill the threads
startKill = time.time()
for t in threadList:
t.quit()
for t in threadList:
t.join()
endKill = time.time()
# Display results
timeCreate = endCreate - startCreate
timeKill = endKill - startKill
print 'Time taken to create threads is %f.' % timeCreate
print 'Time taken to kill threads is %f.' % timeKill
More information about the Python-list
mailing list