Deque.hx 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package java.vm;
  2. import java.Lib;
  3. /**
  4. A Lock-free Queue implementation
  5. **/
  6. @:native('haxe.java.vm.Deque')
  7. @:nativeGen class Deque<T>
  8. {
  9. @:private var head:Node<T>;
  10. @:private var tail:Node<T>;
  11. public function new()
  12. {
  13. this.head = this.tail = new Node(null);
  14. }
  15. public function add(i : T)
  16. {
  17. var n = new Node(i);
  18. untyped __lock__(this,
  19. {
  20. tail.next = n;
  21. tail = n;
  22. try { untyped this.notify(); } catch(e:Dynamic) { throw e; }
  23. });
  24. }
  25. public function push(i : T)
  26. {
  27. var n = new Node(i);
  28. untyped __lock__(this,
  29. {
  30. n.next = head.next;
  31. head.next = n;
  32. try { untyped this.notify(); } catch(e:Dynamic) { throw e; }
  33. });
  34. }
  35. public function pop(block : Bool) : Null<T>
  36. {
  37. var ret = null;
  38. untyped __lock__(this, {
  39. var n = null;
  40. do {
  41. n = head.next;
  42. if (n != null)
  43. {
  44. ret = n.value;
  45. n.value = null;
  46. head = n;
  47. } else if (block) {
  48. //block
  49. try { untyped this.wait(); } catch(e:Dynamic) { throw e; }
  50. }
  51. } while( block && n == null );
  52. });
  53. return ret;
  54. }
  55. }
  56. @:native('haxe.java.vm.DequeNode')
  57. @:nativeGen
  58. class Node<T>
  59. {
  60. public var value:T;
  61. public var next:Node<T>;
  62. public function new(val)
  63. {
  64. this.value = val;
  65. }
  66. }