2
0

EventLoop.hx 7.5 KB

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