Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping a thread after a certain amount of time

I'm looking to terminate some threads after a certain amount of time. These threads will be running an infinite while loop and during this time they can stall for a random, large amount of time. The thread cannot last longer than time set by the duration variable. How can I make it so after the length set by duration, the threads stop.

def main():     t1 = threading.Thread(target=thread1, args=1)     t2 = threading.Thread(target=thread2, args=2)      time.sleep(duration)     #the threads must be terminated after this sleep 
like image 402
Takkun Avatar asked Jun 29 '11 16:06

Takkun


People also ask

How do you stop a thread at a specific time?

You can create a custom class that extends Thread and then implement the method run() and CancelCurrentThread() , your run will start the Thread and CancelCurrentThread() will stop it ignoring the exceptions.

How do you kill a thread after some time Python?

start() # wait 30 seconds for the thread to finish its work t. join(30) if t. is_alive(): print "thread is not done, setting event to kill thread." e. set() else: print "thread has already finished."

When should you stop a thread?

A thread is automatically destroyed when the run() method has completed. But it might be required to kill/stop a thread before it has completed its life cycle. Previously, methods suspend(), resume() and stop() were used to manage the execution of threads.


2 Answers

This will work if you are not blocking.

If you are planing on doing sleeps, its absolutely imperative that you use the event to do the sleep. If you leverage the event to sleep, if someone tells you to stop while "sleeping" it will wake up. If you use time.sleep() your thread will only stop after it wakes up.

import threading import time  duration = 2  def main():     t1_stop = threading.Event()     t1 = threading.Thread(target=thread1, args=(1, t1_stop))      t2_stop = threading.Event()     t2 = threading.Thread(target=thread2, args=(2, t2_stop))      time.sleep(duration)     # stops thread t2     t2_stop.set()  def thread1(arg1, stop_event):     while not stop_event.is_set():         stop_event.wait(timeout=5)  def thread2(arg1, stop_event):     while not stop_event.is_set():         stop_event.wait(timeout=5) 
like image 103
Nix Avatar answered Oct 03 '22 02:10

Nix


If you want the threads to stop when your program exits (as implied by your example), then make them daemon threads.

If you want your threads to die on command, then you have to do it by hand. There are various methods, but all involve doing a check in your thread's loop to see if it's time to exit (see Nix's example).

like image 21
Seth Avatar answered Oct 03 '22 03:10

Seth