Deque.hx 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * Copyright (C)2005-2015 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 java.vm;
  23. import java.Lib;
  24. /**
  25. A Lock-free Queue implementation
  26. **/
  27. @:native('haxe.java.vm.Deque')
  28. @:nativeGen class Deque<T>
  29. {
  30. @:private var head:Node<T>;
  31. @:private var tail:Node<T>;
  32. public function new()
  33. {
  34. this.head = this.tail = new Node(null);
  35. }
  36. public function add(i : T)
  37. {
  38. var n = new Node(i);
  39. untyped __lock__(this,
  40. {
  41. tail.next = n;
  42. tail = n;
  43. try { untyped this.notify(); } catch(e:Dynamic) { throw e; }
  44. });
  45. }
  46. public function push(i : T)
  47. {
  48. var n = new Node(i);
  49. untyped __lock__(this,
  50. {
  51. n.next = head.next;
  52. head.next = n;
  53. try { untyped this.notify(); } catch(e:Dynamic) { throw e; }
  54. });
  55. }
  56. public function pop(block : Bool) : Null<T>
  57. {
  58. var ret = null;
  59. untyped __lock__(this, {
  60. var n = null;
  61. do {
  62. n = head.next;
  63. if (n != null)
  64. {
  65. ret = n.value;
  66. n.value = null;
  67. head = n;
  68. } else if (block) {
  69. //block
  70. try { untyped this.wait(); } catch(e:Dynamic) { throw e; }
  71. }
  72. } while( block && n == null );
  73. });
  74. return ret;
  75. }
  76. }
  77. @:native('haxe.java.vm.DequeNode')
  78. @:nativeGen
  79. class Node<T>
  80. {
  81. public var value:T;
  82. public var next:Node<T>;
  83. public function new(val)
  84. {
  85. this.value = val;
  86. }
  87. }