EventLoop.hx 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. package sys.thread;
  2. /**
  3. When an event loop has an available event to execute.
  4. **/
  5. enum NextEventTime {
  6. /** There's already an event waiting to be executed */
  7. Now;
  8. /** No new events are expected. */
  9. Never;
  10. /**
  11. An event is expected to arrive at any time.
  12. If `time` is specified, then the event will be ready at that time for sure.
  13. */
  14. AnyTime(time:Null<Float>);
  15. /** An event is expected to be ready for execution at `time`. */
  16. At(time:Float);
  17. }
  18. /**
  19. An event loop implementation used for `sys.thread.Thread`
  20. **/
  21. @:coreApi
  22. class EventLoop {
  23. final mutex = new Mutex();
  24. final oneTimeEvents = new Array<Null<()->Void>>();
  25. var oneTimeEventsIdx = 0;
  26. final waitLock = new Lock();
  27. var promisedEventsCount = 0;
  28. var regularEvents:Null<RegularEvent>;
  29. public function new():Void {}
  30. /**
  31. Schedule event for execution every `intervalMs` milliseconds in current loop.
  32. **/
  33. public function repeat(event:()->Void, intervalMs:Int):EventHandler {
  34. mutex.acquire();
  35. var interval = 0.001 * intervalMs;
  36. var event = new RegularEvent(event, Sys.time() + interval, interval);
  37. inline insertEventByTime(event);
  38. waitLock.release();
  39. mutex.release();
  40. return event;
  41. }
  42. function insertEventByTime(event:RegularEvent):Void {
  43. switch regularEvents {
  44. case null:
  45. regularEvents = event;
  46. case current:
  47. var previous = null;
  48. while(true) {
  49. if(current == null) {
  50. previous.next = event;
  51. event.previous = previous;
  52. break;
  53. } else if(event.nextRunTime < current.nextRunTime) {
  54. event.next = current;
  55. current.previous = event;
  56. switch previous {
  57. case null:
  58. regularEvents = event;
  59. case _:
  60. event.previous = previous;
  61. previous.next = event;
  62. current.previous = event;
  63. }
  64. break;
  65. } else {
  66. previous = current;
  67. current = current.next;
  68. }
  69. }
  70. }
  71. }
  72. /**
  73. Prevent execution of a previously scheduled event in current loop.
  74. **/
  75. public function cancel(eventHandler:EventHandler):Void {
  76. mutex.acquire();
  77. var event:RegularEvent = eventHandler;
  78. event.cancelled = true;
  79. if(regularEvents == event) {
  80. regularEvents = event.next;
  81. }
  82. switch event.next {
  83. case null:
  84. case e: e.previous = event.previous;
  85. }
  86. switch event.previous {
  87. case null:
  88. case e: e.next = event.next;
  89. }
  90. mutex.release();
  91. }
  92. /**
  93. Notify this loop about an upcoming event.
  94. This makes the thread to stay alive and wait for as many events as many times
  95. `.promise()` was called. These events should be added via `.runPromised()`
  96. **/
  97. public function promise():Void {
  98. mutex.acquire();
  99. ++promisedEventsCount;
  100. mutex.release();
  101. }
  102. /**
  103. Execute `event` as soon as possible.
  104. **/
  105. public function run(event:()->Void):Void {
  106. mutex.acquire();
  107. oneTimeEvents[oneTimeEventsIdx++] = event;
  108. waitLock.release();
  109. mutex.release();
  110. }
  111. /**
  112. Add previously promised `event` for execution.
  113. **/
  114. public function runPromised(event:()->Void):Void {
  115. mutex.acquire();
  116. oneTimeEvents[oneTimeEventsIdx++] = event;
  117. --promisedEventsCount;
  118. waitLock.release();
  119. mutex.release();
  120. }
  121. /**
  122. Executes all pending events.
  123. The returned time stamps can be used with `Sys.time()` for calculations.
  124. Depending on a target platform this method may be non-reentrant. It must
  125. not be called from event callbacks.
  126. **/
  127. public function progress():NextEventTime {
  128. return switch __progress(Sys.time(), [], []) {
  129. case {nextEventAt:-2}: Now;
  130. case {nextEventAt:-1, anyTime:false}: Never;
  131. case {nextEventAt:-1, anyTime:true}: AnyTime(null);
  132. case {nextEventAt:time, anyTime:true}: AnyTime(time);
  133. case {nextEventAt:time, anyTime:false}: At(time);
  134. }
  135. }
  136. /**
  137. Blocks until a new event is added or `timeout` (in seconds) to expires.
  138. Depending on a target platform this method may also automatically execute arriving
  139. events while waiting. However if any event is executed it will stop waiting.
  140. Returns `true` if more events are expected.
  141. Returns `false` if no more events expected.
  142. Depending on a target platform this method may be non-reentrant. It must
  143. not be called from event callbacks.
  144. **/
  145. public function wait(?timeout:Float):Bool {
  146. return waitLock.wait(timeout);
  147. }
  148. /**
  149. Execute all pending events.
  150. Wait and execute as many events as many times `promiseEvent()` was called.
  151. Runs until all repeating events are cancelled and no more events is expected.
  152. Depending on a target platform this method may be non-reentrant. It must
  153. not be called from event callbacks.
  154. **/
  155. public function loop():Void {
  156. var recycleRegular = [];
  157. var recycleOneTimers = [];
  158. while(true) {
  159. var r = __progress(Sys.time(), recycleRegular, recycleOneTimers);
  160. switch r {
  161. case {nextEventAt:-2}:
  162. case {nextEventAt:-1, anyTime:false}:
  163. break;
  164. case {nextEventAt:-1, anyTime:true}:
  165. waitLock.wait();
  166. case {nextEventAt:time}:
  167. var timeout = time - Sys.time();
  168. waitLock.wait(Math.max(0, timeout));
  169. }
  170. }
  171. }
  172. /**
  173. `.progress` implementation with a reusable array for internal usage.
  174. The `nextEventAt` field of the return value denotes when the next event
  175. is expected to run:
  176. * -1 - never
  177. * -2 - now
  178. * other values - at specified time
  179. **/
  180. inline function __progress(now:Float, recycleRegular:Array<RegularEvent>, recycleOneTimers:Array<()->Void>):{nextEventAt:Float, anyTime:Bool} {
  181. var regularsToRun = recycleRegular;
  182. var eventsToRunIdx = 0;
  183. // When the next event is expected to run
  184. var nextEventAt:Float = -1;
  185. mutex.acquire();
  186. //reset waitLock
  187. while(waitLock.wait(0.0)) {}
  188. // Collect regular events to run
  189. var current = regularEvents;
  190. while(current != null) {
  191. if(current.nextRunTime <= now) {
  192. regularsToRun[eventsToRunIdx++] = current;
  193. current.nextRunTime += current.interval;
  194. nextEventAt = -2;
  195. } else if(nextEventAt == -1 || current.nextRunTime < nextEventAt) {
  196. nextEventAt = current.nextRunTime;
  197. }
  198. current = current.next;
  199. }
  200. mutex.release();
  201. // Run regular events
  202. for(i in 0...eventsToRunIdx) {
  203. if(!regularsToRun[i].cancelled)
  204. regularsToRun[i].run();
  205. regularsToRun[i] = null;
  206. }
  207. eventsToRunIdx = 0;
  208. var oneTimersToRun = recycleOneTimers;
  209. // Collect pending one-time events
  210. mutex.acquire();
  211. for(i => event in oneTimeEvents) {
  212. switch event {
  213. case null:
  214. break;
  215. case _:
  216. oneTimersToRun[eventsToRunIdx++] = event;
  217. oneTimeEvents[i] = null;
  218. }
  219. }
  220. oneTimeEventsIdx = 0;
  221. var hasPromisedEvents = promisedEventsCount > 0;
  222. mutex.release();
  223. //run events
  224. for(i in 0...eventsToRunIdx) {
  225. oneTimersToRun[i]();
  226. oneTimersToRun[i] = null;
  227. }
  228. // Some events were executed. They could add new events to run.
  229. if(eventsToRunIdx > 0) {
  230. nextEventAt = -2;
  231. }
  232. return {nextEventAt:nextEventAt, anyTime:hasPromisedEvents}
  233. }
  234. }
  235. abstract EventHandler(RegularEvent) from RegularEvent to RegularEvent {}
  236. private class RegularEvent {
  237. public var nextRunTime:Float;
  238. public final interval:Float;
  239. public final run:()->Void;
  240. public var next:Null<RegularEvent>;
  241. public var previous:Null<RegularEvent>;
  242. public var cancelled:Bool = false;
  243. public function new(run:()->Void, nextRunTime:Float, interval:Float) {
  244. this.run = run;
  245. this.nextRunTime = nextRunTime;
  246. this.interval = interval;
  247. }
  248. }