Deque.hx 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * Copyright (C)2005-2019 Haxe Foundation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. * DEALINGS IN THE SOFTWARE.
  21. */
  22. package sys.thread;
  23. using python.internal.UBuiltins;
  24. class Deque<T> {
  25. var deque:NativeDeque<T>;
  26. var lock:NativeCondition;
  27. public function new() {
  28. deque = new NativeDeque<T>();
  29. lock = new NativeCondition();
  30. }
  31. public function add(i:T) {
  32. lock.acquire();
  33. deque.append(i);
  34. lock.notify();
  35. lock.release();
  36. }
  37. public function push(i:T) {
  38. lock.acquire();
  39. deque.appendleft(i);
  40. lock.notify();
  41. lock.release();
  42. }
  43. public function pop(block:Bool):Null<T> {
  44. var ret = null;
  45. lock.acquire();
  46. if (block) {
  47. lock.wait_for(() -> deque.bool());
  48. ret = deque.popleft();
  49. } else if (deque.bool()) {
  50. ret = deque.popleft();
  51. }
  52. lock.release();
  53. return ret;
  54. }
  55. }
  56. @:pythonImport("collections", "deque")
  57. @:native("deque")
  58. private extern class NativeDeque<T> {
  59. function new();
  60. function append(x:T):Void;
  61. function appendleft(x:T):Void;
  62. function popleft():T;
  63. }
  64. @:pythonImport("threading", "Condition")
  65. @:native("Condition")
  66. private extern class NativeCondition {
  67. function new(?lock:Dynamic);
  68. function acquire(blocking:Bool = true, timeout:Float = -1):Bool;
  69. function release():Void;
  70. function wait(?timeout:Float):Bool;
  71. function wait_for(predicate:()->Bool, ?timeout:Float):Bool;
  72. function notify(n:Int = 1):Void;
  73. function notify_all():Void;
  74. }