Deque.hx 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. import python.lib.threading.Condition;
  24. using python.internal.UBuiltins;
  25. class Deque<T> {
  26. var deque:NativeDeque<T>;
  27. var lock:Condition;
  28. public function new() {
  29. deque = new NativeDeque<T>();
  30. lock = new Condition();
  31. }
  32. public function add(i:T) {
  33. lock.acquire();
  34. deque.append(i);
  35. lock.notify();
  36. lock.release();
  37. }
  38. public function push(i:T) {
  39. lock.acquire();
  40. deque.appendleft(i);
  41. lock.notify();
  42. lock.release();
  43. }
  44. public function pop(block:Bool):Null<T> {
  45. var ret = null;
  46. lock.acquire();
  47. if (block) {
  48. lock.wait_for(() -> deque.bool());
  49. ret = deque.popleft();
  50. } else if (deque.bool()) {
  51. ret = deque.popleft();
  52. }
  53. lock.release();
  54. return ret;
  55. }
  56. }
  57. @:pythonImport("collections", "deque")
  58. @:native("deque")
  59. private extern class NativeDeque<T> {
  60. function new();
  61. function append(x:T):Void;
  62. function appendleft(x:T):Void;
  63. function popleft():T;
  64. }