Python:如何停止线程的工作

时间:2013-11-28 12:43:35

标签: python multithreading

我是python的新手,我正在努力使代码在达到超时的情况下停止工作。但似乎胎面正确超时但它并没有停止工作。

这是我的代码:

    import threading
    import time
    import sys

    def main():
        t1_stop= threading.Event()
        t1 = threading.Thread(target=thread1, args=(5, t1_stop))
        t1.setDaemon(False)
        t1.start()
        print 'thread 1 set'
        while True:
            print "blablabla"
            time.sleep(1)

    def thread1(time, stop_event):
        while(not stop_event.is_set()):
            #equivalent to time.sleep()
            print 'thread 1'
            stop_event.wait(time)

    main()

UPD 我使用Timer而不是time.time来更新代码。

  • def main():
           stopped = threading.Event()
           timeout = 10
           #thread = threading.Thread(target=my_thread, args=(timeout, stopped))
           timer = Timer(timeout, my_thread(timeout,stopped))
           thread = threading.Thread((timer).start())
           thread.setDaemon(False)
           #thread.start()
           print 'thread 1 set'
           start_t = time.time()
           while thread.is_alive():
               print "doing my job"
               if not stopped.is_set():# and (time.time() - start_t) > timeout:
                   stopped.set()
               #time.sleep(1)
    
       def my_thread(time, stopped):
           while not stopped.wait(time): 
               print('thread stopped')
    
       main()
    

但我仍然遇到原始问题,脚本没有停止并继续。


提前感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

你必须在main函数中调用t1_stop.set()来停止线程。

类似的东西:

import threading
import time
import sys

def main():
    stopped = threading.Event()
    thread = threading.Thread(target=my_thread, args=(5, stopped))
    thread.setDaemon(False)
    thread.start()
    print 'thread 1 set'
    time.sleep(5) # +
    stopped.set() # +
    while True:
        print "blablabla"
        time.sleep(1)

def my_thread(time, stopped):
    while not stopped.wait(time): 
        print('thread 1')

main()

与'blablabla':

def main():
    ...
    thread.start()
    print 'thread 1 set'
    start_t = time.time()
    while True:
        print "blablabla"
        if not stopped.is_set() and (time.time() - start_t) > 5:
            stopped.set()
        time.sleep(1)

UPD:

退出while

    while thread.is_alive():
        print "blablabla"
        if not stopped.is_set() and (time.time() - start_t) > 5:
            stopped.set()
        time.sleep(1)