Locker.php 934 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Coroutine;
  12. use Hyperf\Engine\Channel;
  13. class Locker
  14. {
  15. /**
  16. * @var Channel[]
  17. */
  18. protected static array $channels = [];
  19. public static function lock(string $key): bool
  20. {
  21. if (! isset(static::$channels[$key])) {
  22. static::$channels[$key] = new Channel(1);
  23. return true;
  24. }
  25. $channel = static::$channels[$key];
  26. $channel->pop(-1);
  27. return false;
  28. }
  29. public static function unlock(string $key): void
  30. {
  31. if (isset(static::$channels[$key])) {
  32. $channel = static::$channels[$key];
  33. static::$channels[$key] = null;
  34. $channel->close();
  35. }
  36. }
  37. }