threadingTkInter.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. def tkMainThreadPoller(tk, queue):
  16. """
  17. The polling function to register with Tk at the start. This will do the actual scheduling in Tk.
  18. :param tk: the Tk instance to use
  19. :param queue: the queue to check
  20. """
  21. global tkRunningID
  22. while 1:
  23. try:
  24. time, func = queue.popleft()
  25. tkRunningID = tk.after(time, func)
  26. except TypeError:
  27. # Was an invalidation call
  28. try:
  29. if tkRunningID is not None:
  30. tk.after_cancel(tkRunningID)
  31. except IndexError:
  32. # Nothing to cancel
  33. pass
  34. tkRunningID = None
  35. except IndexError:
  36. break
  37. tk.after(10, tkMainThreadPoller, tk, queue)
  38. class ThreadingTkInter(object):
  39. """
  40. Tk Inter subsystem for realtime simulation
  41. """
  42. def __init__(self, tk):
  43. """
  44. Constructor
  45. :param queue: the queue object that is also used by the main thread to put events on the main Tk object
  46. """
  47. self.runningID = None
  48. self.last_infinity = False
  49. import collections
  50. queue = collections.deque()
  51. self.queue = queue
  52. tk.after(10, tkMainThreadPoller, tk, queue)
  53. def unlock(self):
  54. """
  55. Unlock the waiting thread
  56. """
  57. # Don't get it normally, as it would seem like a method call
  58. getattr(self, "func")()
  59. def wait(self, t, func):
  60. """
  61. Wait for the specified time, or faster if interrupted
  62. :param t: time to wait
  63. :param func: the function to call
  64. """
  65. if t == float('inf'):
  66. self.last_infinity = True
  67. else:
  68. self.last_infinity = False
  69. self.func = func
  70. self.queue.append((int(t*1000), self.unlock))
  71. def interrupt(self):
  72. """
  73. Interrupt the waiting thread
  74. """
  75. if not self.last_infinity:
  76. self.queue.append(None)
  77. self.unlock()