Semaphore.hx 688 B

123456789101112131415161718192021222324252627282930313233343536
  1. package sys.thread;
  2. @:coreApi class Semaphore {
  3. final native:eval.luv.Semaphore;
  4. public function new(value:Int):Void {
  5. native = eval.luv.Semaphore.init(value).resolve();
  6. eval.vm.Gc.finalise(destroy, this);
  7. }
  8. static function destroy(sem:Semaphore):Void {
  9. sem.native.destroy();
  10. }
  11. public function acquire():Void {
  12. native.wait();
  13. }
  14. public function tryAcquire(?timeout:Float):Bool {
  15. if (timeout == null) {
  16. return native.tryWait().isOk();
  17. } else {
  18. var t = Sys.time() + timeout;
  19. while (Sys.time() < t) {
  20. if (native.tryWait().isOk()) {
  21. return true;
  22. }
  23. }
  24. return false;
  25. }
  26. }
  27. public function release():Void {
  28. native.post();
  29. }
  30. }