Robot Framework
windows.py
Go to the documentation of this file.
1 # Copyright 2008-2015 Nokia Networks
2 # Copyright 2016- Robot Framework Foundation
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 
16 import ctypes
17 import time
18 from threading import current_thread, Lock, Timer
19 
20 
21 class Timeout:
22 
23  def __init__(self, timeout, error):
24  self._runner_thread_id_runner_thread_id = current_thread().ident
25  self._timer_timer = Timer(timeout, self._timed_out_timed_out)
26  self._error_error = error
27  self._timeout_occurred_timeout_occurred = False
28  self._finished_finished = False
29  self._lock_lock = Lock()
30 
31  def execute(self, runnable):
32  try:
33  self._start_timer_start_timer()
34  try:
35  result = runnable()
36  finally:
37  self._cancel_timer_cancel_timer()
38  self._wait_for_raised_timeout_wait_for_raised_timeout()
39  return result
40  finally:
41  if self._timeout_occurred_timeout_occurred:
42  raise self._error_error
43 
44  def _start_timer(self):
45  self._timer_timer.start()
46 
47  def _cancel_timer(self):
48  with self._lock_lock:
49  self._finished_finished = True
50  self._timer_timer.cancel()
51 
53  if self._timeout_occurred_timeout_occurred:
54  while True:
55  time.sleep(0)
56 
57  def _timed_out(self):
58  with self._lock_lock:
59  if self._finished_finished:
60  return
61  self._timeout_occurred_timeout_occurred = True
62  self._raise_timeout_raise_timeout()
63 
64  def _raise_timeout(self):
65  # See, for example, http://tomerfiliba.com/recipes/Thread2/
66  # for more information about using PyThreadState_SetAsyncExc
67  tid = ctypes.c_long(self._runner_thread_id_runner_thread_id)
68  error = ctypes.py_object(type(self._error_error))
69  while ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, error) > 1:
70  ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
71  time.sleep(0) # give time for other threads
def __init__(self, timeout, error)
Definition: windows.py:23