0

I try to use "join" to manage and stop those threads that cost too much time. And, I use "While" in threads to keep threads always running. However, I find that these threads will never stop. How can I manage a thread that cost too much time? Thank you!

import threading, time


def doThreadTest():
    print 'start thread time:', time.strftime('%H:%M:%S')
    while 1:
        print 1
    print 'stop thread time:', time.strftime('%H:%M:%S')


threads = []
for i in range(2):
    thread1 = threading.Thread(target=doThreadTest)
    # thread1.setDaemon(True)

    threads.append(thread1)

for t in threads:
    t.start()

for t in threads:
    t.join(5)  # I use join(5) to stop a thread if it cost more than 5s
print 'stop main thread', time.strftime('%H:%M:%S')
Shusen Wu
  • 27
  • 6
  • I don't see in your example how you have attempted to stop the thread - nor can I see any timeouts defined. What have you tried? – Shadow Nov 15 '17 at 04:21
  • I use join(5) to stop the thread. I assume the thread will be stopped by 5s – Shusen Wu Nov 15 '17 at 04:28
  • Ah. That'll wait 5 seconds for the thread to close - then give up and leave it running. Because you have it in a for loop, it'll take `threads * 5` seconds to do so. – Shadow Nov 15 '17 at 04:32
  • 1
    Possible duplicate of [understanding thread.join(timeout)](https://stackoverflow.com/questions/24855335/understanding-thread-jointimeout) – Shadow Nov 15 '17 at 04:32
  • Thank you very much. Does it mean the thread will keep running because the loop but the join(5) will stop wait in the main thread. So, if I set the main thread as daemon thread, then after join(), the main thread stop and all the threads stops? – Shusen Wu Nov 15 '17 at 04:38
  • The threads keep running after the `join`s time out, unless you make them daemon threads. –  Nov 15 '17 at 04:38
  • Possible duplicate of [what is the use of join() in python threading](https://stackoverflow.com/questions/15085348/what-is-the-use-of-join-in-python-threading) –  Nov 15 '17 at 04:39

0 Answers0