简体   繁体   中英

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. 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.

  •  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.

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':

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:

exiting from while :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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