Mutex.hx 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package java.vm;
  2. @:native('haxe.java.vm.Mutex') class Mutex
  3. {
  4. @:private var owner:java.lang.Thread;
  5. @:private var lockCount:Int = 0;
  6. /**
  7. Creates a mutex, which can be used to acquire a temporary lock to access some resource.
  8. The main difference with a lock is that a mutex must always be released by the owner thread
  9. **/
  10. public function new()
  11. {
  12. }
  13. /**
  14. Try to acquire the mutex, returns true if acquire or false if it's already locked by another thread.
  15. **/
  16. public function tryAcquire():Bool
  17. {
  18. var ret = false, cur = java.lang.Thread.currentThread();
  19. untyped __lock__(this, {
  20. var expr = null;
  21. if (owner == null)
  22. {
  23. ret = true;
  24. if(lockCount != 0) throw "assert";
  25. lockCount = 1;
  26. owner = cur;
  27. } else if (owner == cur) {
  28. ret = true;
  29. owner = cur;
  30. lockCount++;
  31. }
  32. });
  33. return ret;
  34. }
  35. /**
  36. The current thread acquire the mutex or wait if not available.
  37. The same thread can acquire several times the same mutex, but must release it as many times it has been acquired.
  38. **/
  39. public function acquire():Void
  40. {
  41. var cur = java.lang.Thread.currentThread();
  42. untyped __lock__(this, {
  43. var expr = null;
  44. if (owner == null)
  45. {
  46. owner = cur;
  47. if (lockCount != 0) throw "assert";
  48. lockCount = 1;
  49. } else if (owner == cur) {
  50. lockCount++;
  51. } else {
  52. try { untyped this.wait(); } catch(e:Dynamic) { throw e; }
  53. lockCount = 1;
  54. owner = cur;
  55. }
  56. });
  57. }
  58. /**
  59. Release a mutex that has been acquired by the current thread. If the current thread does not own the mutex, an exception will be thrown
  60. **/
  61. public function release():Void
  62. {
  63. var cur = java.lang.Thread.currentThread();
  64. untyped __lock__(this, {
  65. var expr = null;
  66. if (owner != cur) {
  67. throw "This mutex isn't owned by the current thread!";
  68. }
  69. if (--lockCount == 0)
  70. {
  71. this.owner = null;
  72. untyped this.notify();
  73. }
  74. });
  75. }
  76. }