Skip to content Skip to sidebar Skip to footer

How To Kill A Thread After N Seconds?

I want to create threads that will add something to an array, but, if they don't do that in less than 2 seconds, I want to terminate them. This is a prof of concept, so the code is

Solution 1:

As I said in a comment you can't really "kill" a thread (externally). However they can "commit suicide" by returning or raising a exception.

Below is example of doing the latter when the thread's execution time has exceeded a given amount of time. Note that this is not the same as doing a join(timeout) call, which only blocks until the thread ends or the specified amount of time has elapsed. That's why the printing of value and its appending to the list happens regardless of whether the thread finishes before the call to join() times-out or not.

I got the basic idea of using sys.settrace() from the tutorial titled Different ways to kill a Thread — although my implementation is slightly different. Also note that this approach likely introduces a significant amount of overhead.

import sys
import threading
import time


classTimelimitedThread(threading.Thread):
    def__init__(self, *args, time_limit, **kwargs):
        self.time_limit = time_limit
        self._run_backup = self.run  # Save superclass run() method.
        self.run = self._run  # Change it to custom version.super().__init__(*args, **kwargs)

    def_run(self):
        self.start_time = time.time()
        sys.settrace(self.globaltrace)
        self._run_backup()  # Call superclass run().
        self.run = self._run_backup  # Restore original.defglobaltrace(self, frame, event, arg):
        return self.localtrace if event == 'call'elseNonedeflocaltrace(self, frame, event, arg):
        if(event == 'line'and
           time.time()-self.start_time > self.time_limit):  # Over time?raise SystemExit()  # Terminate thread.return self.localtrace


THREAD_TIME_LIMIT = 2.1# Secs
threads = []
my_list = []

deffoo(value):
    global my_list
    time.sleep(value)
    print("Value: {}".format(value))
    my_list.append(value)

for i inrange(5):
    th = TimelimitedThread(target=foo, args=(i,), time_limit=THREAD_TIME_LIMIT)
    threads.append(th)

for th in threads:
    th.start()

for th in threads:
    th.join()

print('\nResults:')
print('my_list:', my_list)

Output:

Value: 0
Value: 1
Value: 2

Results:
my_list: [0, 1, 2]

Solution 2:

Join() is used to wait for the respective thread to finish. To terminate a thread, use stop().. You can try as follows: time.sleep(N) th.join()

Post a Comment for "How To Kill A Thread After N Seconds?"