14

So the timeout param, for a thread, should stop the thread after timeout seconds (if it hasn't terminated yet).

In my software I'm trying to replace a Queue.Queue.join() (it contains an item for every thread: each thread will run Queue.Queue.task_done()) that could stop the software if a thread doesn't terminate. So if a thread, among other 50, doesn't terminate then it is all freezed.

I want that every thread stops in 5 seconds, for example. So i will start each thread with timeout of 5 seconds. Is it correct?

CODE

import threading
import time

def tt(name, num):
    while True:
        num += 0.5
        print 'thread ' + str(name) + ' at time ' + str(num)
        time.sleep(0.5)


for i in range(3):
    t=threading.Thread(target=tt, args=(i, 0))
    t.setDaemon(True)
    t.start()
    t.join(timeout=1)

print 'end'

RESULT

It is not properly working.. every thread should stop after 1 second. Thread 0 stops after 3 secs, thread 1 after 2 secs.

thread 0 at time 0.5
thread 0 at time 1.0
thread 1 at time 0.5
thread 0 at time 1.5
thread 0 at time 2.0
thread 1 at time 1.0
thread 2 at time 0.5
thread 0 at time 2.5
thread 1 at time 1.5
thread 2 at time 1.0thread 1 at time 2.0

thread 0 at time 3.0
end
Vivz
  • 6,625
  • 2
  • 17
  • 33
FrancescoN
  • 2,146
  • 12
  • 34
  • 45

1 Answers1

38

You're misunderstanding what timeout does. It just tells join how long to wait for the thread to stop. If the thread is still running after the timeout expires, the join call ends, but the thread keeps running.

From the docs:

When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call isAlive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out.

dano
  • 91,354
  • 19
  • 222
  • 219
  • ok.. so if i started 3 threads they wouldn't stop. But they stopped.. why? – FrancescoN Jul 20 '14 at 22:14
  • @Jimmy5nomama they're being ended when your main thread ends, because you used `setDaemon(True) `. – dano Jul 20 '14 at 22:25
  • 1
    but if i set them as Daemons, they should go on on their own, while the main can go ahead by its own (without the join()). Correct me if it is wrong, please – FrancescoN Jul 20 '14 at 22:29
  • 5
    @Jimmy5nomama the `daemon` flag tells Python that the thread shouldn't keep the program alive if the main thread is complete. If `daemon` is False, the program will stay alive until the thread is complete, even if the main thread is finished. – dano Jul 20 '14 at 22:32
  • Thank you very much, one last thing.. do you know how could i do to start threads that stop within *timeout* seconds? Should i use this http://stackoverflow.com/a/14924210/1647254? – FrancescoN Jul 20 '14 at 22:47