Guest User

Untitled

a guest
Feb 21st, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. class WaiterTimeout(Exception):
  2. pass
  3.  
  4.  
  5. class Waiter(object):
  6. """
  7. w = Waiter()
  8. run_some_func_with_callback(callback=lambda x: w.stop(x))
  9. try:
  10. r = w.timeout(5) # wait 5 seconds for timeout
  11. except WaiterTimeout:
  12. print("timeout occured")
  13. else:
  14. print("result: {}".format(r))
  15. """
  16.  
  17. def __init__(self, spin=None):
  18. self.event = threading.Event()
  19. self.result = None
  20.  
  21. def wait(self, timeout=None, spin=0):
  22. if timeout is None or not spin:
  23. if self.event.wait(timeout):
  24. return self.result
  25. else:
  26. raise WaiterTimeout
  27.  
  28. total = 0
  29. while total < timeout:
  30. if self.event.wait(spin):
  31. return self.result
  32. total += spin
  33.  
  34. raise WaiterTimeout
  35.  
  36. def stop(self, result=None):
  37. self.result = result
  38. self.event.set()
  39.  
  40. def clear(self):
  41. self.event.clear()
  42. self.result = None
Add Comment
Please, Sign In to add comment