thread join() not stopping

M

mclaugb

Here is a simple piece of thread code.
When i add the print (or other) function into the run method--the thread
fails to stop after 2 seconds which the join(2) should ensure.
I have a function that I must have timeout and cannot figure a way to do
this.

Any help appreciated. Should compile on 2.4

Bryan

import time
from threading import Thread

class MyThread(Thread):

def __init__(self,mybignum):

Thread.__init__(self)

self.mybignum=mybignum

def run(self):

for l in range(10):
for k in range(self.mybignum):
res=0
for i in range(self.mybignum):
res+=1
#########################################
print "not stopping"
##########################################

def myadd_nothread(bignum):

for l in range(10):
for k in range(bignum):
res=0
for i in range(bignum):
res+=1


for l in range(10):
for k in range(bignum):
res=0
for i in range(bignum):
res+=1



def thread_test(bignum):
#We create 2 Thread objects for the 2 threads.
thr1=MyThread(bignum)
thr2=MyThread(bignum)

thr1.start()
thr2.start()

thr1.join(2)
thr2.join(2)


def test():

bignum=150
#Let us test the threading part

starttime=time.clock()
thread_test(bignum)
stoptime=time.clock()

print "Running 2 threads took %.3f seconds" % (stoptime-starttime)

#Now run without Threads.
starttime=time.clock()
myadd_nothread(bignum)
stoptime=time.clock()

print "Running Without Threads took %.3f seconds" % (stoptime-starttime)


if __name__=="__main__":

test()
 
P

Peter Otten

mclaugb said:
When i add the print (or other) function into the run method--the thread
fails to stop after 2 seconds which the join(2) should ensure.

The calling thread waits until the thread you call join() upon stops or 2
seconds have passed -- whatever occurs first.


import time
from threading import Thread

class MyThread(Thread):
tick = 0.1
def __init__(self, seconds):
Thread.__init__(self)
self.n = int(seconds/self.tick)
def run(self):
for i in range(self.n):
time.sleep(self.tick)
print "running"

def measure(seconds):
print "Run for %.2f seconds..." % seconds
t = MyThread(seconds)
t.setDaemon(True)
t.start()
starttime = time.time()
t.join(1) # wait one second
stoptime = time.time()
print stoptime-starttime
t.join() # wait for how long t takes to terminate
print "...done"

if __name__=="__main__":
measure(1.5)
measure(0.5)

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

No members online now.

Forum statistics

Threads
473,836
Messages
2,569,748
Members
45,545
Latest member
rapter____0

Latest Threads

Top