LockManager.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. * Check if a lock with the given identifier exists in the container.
  41. */
  42. public static function exists(string $identifier): bool
  43. {
  44. return isset(static::$container[$identifier]);
  45. }
  46. /**
  47. * Remove the Lock by the identifier from container after used,
  48. * otherwise will occur memory leaks.
  49. */
  50. public static function clear(string $identifier): void
  51. {
  52. unset(static::$container[$identifier]);
  53. }
  54. }