def the_wrapper_around_the_original_function(*args, **kwargs): from kthread import KThread thread = KThread( target=lambda: function_to_decorate(*args, **kwargs)) thread.start() thread.join(timeout=seconds) if thread.is_alive(): thread.kill() if raise_timeout: raise TimeoutError()
class DefaultKThreadTestCase(unittest.TestCase): def setUp(self): self.kthread = KThread(name = "DefaultKThreadTestThread", target = infinite_loop_func) def runTest(self): self.kthread.start() self.assertTrue(self.kthread.isAlive(), "KThread failed to start") # let it run for some time time.sleep(5) self.kthread.terminate() # give it time to process exception time.sleep(1) self.assertFalse(self.kthread.isAlive(), "KThread failed to stop") def tearDown(self): self.kthread.join() self.kthread = None
def _(*args, **kwargs): result = [] new_kwargs = { # create new args for _new_func, because we want to get the func return val to result list 'oldfunc': func, 'result': result, 'oldfunc_args': args, 'oldfunc_kwargs': kwargs } thd = KThread(target=_new_func, args=(), kwargs=new_kwargs) thd.start() thd.join( seconds ) # join(timeout) is for this thread blocked to wait its sub-thread timeout seconds alive = thd.isAlive( ) # isAlive() to check if sub-thread timeouts after timeout seconds thd.kill() # kill the child thread if alive: # raise Timeout(u'function run too long, timeout %d seconds.' % seconds) try: raise Timeout( u'function run too long, timeout %d seconds.' % seconds) finally: return u'function run too long, timeout %d seconds.' % seconds else: return result[0]