<s> import ctypes <EOL> import thread <EOL> import time <EOL> from threading import Timer <EOL> from robotide . lib . robot . errors import TimeoutError <EOL> class Timeout ( object ) : <EOL> def __init__ ( self , timeout , timeout_error ) : <EOL> self . _runner_thread_id = thread . get_ident ( ) <EOL> self . _timeout_error = self . _create_timeout_error_class ( timeout_error ) <EOL> self . _timer = Timer ( timeout , self . _raise_timeout_error ) <EOL> self . _timeout_occurred = False <EOL> def _create_timeout_error_class ( self , timeout_error ) : <EOL> return type ( TimeoutError . __name__ , <EOL> ( TimeoutError , ) , <EOL> { '<STR_LIT>' : lambda self : timeout_error } ) <EOL> def execute ( self , runnable ) : <EOL> self . _start_timer ( ) <EOL> try : <EOL> return runnable ( ) <EOL> finally : <EOL> self . _stop_timer ( ) <EOL> def _start_timer ( self ) : <EOL> self . _timer . start ( ) <EOL> def _stop_timer ( self ) : <EOL> self . _timer . cancel ( ) <EOL> if self . _timeout_occurred : <EOL> self . _cancel_exception ( ) <EOL> raise self . _timeout_error ( ) <EOL> def _raise_timeout_error ( self ) : <EOL> self . _timeout_occurred = True <EOL> return_code = self . _try_to_raise_timeout_error_in_runner_thread ( ) <EOL> while return_code > <NUM_LIT:1> : <EOL> self . _cancel_exception ( ) <EOL> time . sleep ( <NUM_LIT:0> ) <EOL> return_code = self . _try_to_raise_timeout_error_in_runner_thread ( ) <EOL> def _try_to_raise_timeout_error_in_runner_thread ( self ) : <EOL> return ctypes . pythonapi . PyThreadState_SetAsyncExc ( <EOL> self . _runner_thread_id , <EOL> ctypes . py_object ( self . _timeout_error ) ) <EOL> def _cancel_exception ( self ) : <EOL> ctypes . pythonapi . PyThreadState_SetAsyncExc ( self . _runner_thread_id , None ) </s>
