LockManager.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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\Memory;
  12. use RuntimeException;
  13. use Swoole\Lock;
  14. class LockManager
  15. {
  16. /**
  17. * A container that use to store Lock.
  18. */
  19. private static array $container = [];
  20. /**
  21. * You should initialize a Lock with the identifier before use it.
  22. */
  23. public static function initialize(string $identifier, int $type = SWOOLE_RWLOCK, string $filename = ''): void
  24. {
  25. static::$container[$identifier] = new Lock($type, $filename);
  26. }
  27. /**
  28. * Get an initialized Lock from container by the identifier.
  29. *
  30. * @throws RuntimeException when the Lock with the identifier has not initialization
  31. */
  32. public static function get(string $identifier): Lock
  33. {
  34. if (! isset(static::$container[$identifier])) {
  35. throw new RuntimeException('The Lock has not initialization yet.');
  36. }
  37. return static::$container[$identifier];
  38. }
  39. /**
  40. * Remove the Lock by the identifier from container after used,
  41. * otherwise will occur memory leaks.
  42. */
  43. public static function clear(string $identifier): void
  44. {
  45. unset(static::$container[$identifier]);
  46. }
  47. }