简体   繁体   English

Python:如何停止线程的工作

[英]Python: how stop work from thread

I am new with python and I am trying to made code that stop work in case timeout has been reached. 我是python的新手,我正在尝试使代码在达到超时的情况下停止工作。 But it seems that the tread correctly timeout but it does not stop the work. 但似乎胎面正确超时但它并没有停止工作。

Here is my code: 这是我的代码:

    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 I update code using Timer instead of time.time. 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() 

But I still get original problem the script does not stopped and continue. 但我仍然得到原始问题脚本没有停止并继续。


Thanks in advance for your help. 在此先感谢您的帮助。

you must call t1_stop.set() in main function for stop thread. 你必须在main函数中调用t1_stop.set()来停止线程。

something like: 就像是:

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()

with 'blablabla': 与'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: UPD:

exiting from while : 退出while

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM