threadingPython.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # Copyright 2014 Modelling, Simulation and Design Lab (MSDL) at
  2. # McGill University and the University of Antwerp (http://msdl.cs.mcgill.ca/)
  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. from threading import Event, Thread, Lock
  16. import pypdevs.accurate_time as time
  17. from pypdevs.infinity import INFINITY
  18. class ThreadingPython(object):
  19. """
  20. Simple Python threads subsystem
  21. """
  22. def __init__(self):
  23. """
  24. Constructor
  25. """
  26. self.evt = Event()
  27. self.evt_lock = Lock()
  28. def wait(self, delay, func):
  29. """
  30. Wait for the specified time, or faster if interrupted
  31. :param delay: time to wait
  32. :param func: the function to call
  33. """
  34. if delay == INFINITY:
  35. return
  36. #NOTE this call has a granularity of 5ms in Python <= 2.7.x in the worst case, so beware!
  37. # the granularity seems to be much better in Python >= 3.x
  38. p = Thread(target=ThreadingPython.callFunc, args=[self, delay, func])
  39. p.daemon = True
  40. p.start()
  41. def interrupt(self):
  42. """
  43. Interrupt the waiting thread
  44. """
  45. self.evt.set()
  46. def callFunc(self, delay, func):
  47. """
  48. Function to call on a seperate thread: will block for the specified time and call the function afterwards
  49. """
  50. with self.evt_lock:
  51. self.evt.wait(delay)
  52. func()
  53. self.evt.clear()